Hello:
See below VBA routine which allows to export multiple Access tables into a single Excel file... it works without any issues, but I'd like to slightly modify it IOT keep/set various Excel formatting requirements (e.g., column width).
Allow me to recap what the current routine accomplishes:
- Exports any Access tables where table name starts with "T1"
- For any table starting with T1, a worksheet is created where worksheet's name = table name (tdfName)
- Excel loses all formatting given the XLSX is overwritten/recreated each time
- Date is appended to Excel filename... if multiple exports on the same day, XLSX will be overwritten
What I'd like to accomplish:
- At a minimum, I'd like to specify the Excel's column width for n columns
- Given I less than 10 fields (columns) that will be created on each sheet, I'm ok with either using "Autofit" for column A:J or specifying each width for columns A:J
Current Issue:
- As mentioned, for each table (tdfName), Excel creates a worksheet.
- As of right now, the line "ExcelWkb.Worksheets("Sheet1").Columns("A:J").Colu mnWidth = 25" references "Sheet1".
- I've tried replacing "Sheet1" with tdfName, but apparently that does not work.
My questions:
- How should VBA line "ExcelWkb.Worksheets("Sheet1").Columns("A:J").Colu mnWidth = 25" be modified so that columns A:J on all exported tdf (worksheets) will be set to width = 25?
- If other code is needed, what additional lines of VBA code are needed to accomplish this task?
Code:Option Compare Database Option Explicit Public Sub ExcelExport() 'Declare variables Dim db As Database Dim xlsFileLoc As String Dim xlsName As String Dim xlsPath As String Dim tdf As TableDef Dim tdfName As String Dim FileExtension As String Dim j As Integer Dim ExcelWkb As Workbook On Error GoTo Export2Excel_Err 'Capture date time stamp as file extension FileExtension = Format(Date, "yyyy-mm-dd") 'Place XLSX into subfolder 'Exports' xlsFileLoc = CurrentProject.Path & "\Exports\" xlsName = "Export -- " & FileExtension & ".xlsx" xlsPath = xlsFileLoc & xlsName If Len(Dir(xlsPath)) > 0 Then Kill xlsPath End If Set db = CurrentDb j = 0 For Each tdf In db.TableDefs tdfName = tdf.Name If Left(tdf.Name, 3) = "T1_" Then 'Increase counter j = j + 1 On Error Resume Next DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, tdfName, xlsPath, True '******** I need some help w/ next line '******** ExcelWkb.Worksheets("Sheet1").Columns("A:J").ColumnWidth = 25 If Err > 0 Then Err.Clear Debug.Print tdfName j = j - 1 Resume nextstep End If End If nextstep: Next On Error GoTo Export2Excel_Err 'Throw message box MsgBox j & " Table(s) Exported to File:" & vbCr & xlsPath, vbInformation, "Export Status" Export2Excel_Exit: Exit Sub Export2Excel_Err: MsgBox Err & " : " & Err.Description, , "Export2Excel()" Resume Export2Excel_Exit End Sub


Access VBA -- Export into Excel -- Keep Certain Format Elements
Reply With Quote

