Exporting to named Excel Sheet

Larnu

Registered User.
Local time
Today, 13:22
Joined
Oct 18, 2012
Messages
32
Hi All,

Is there anyway to rename, or define the name, of a sheet when you export a query to it? I'm producing a report which makes several queries to a table, but changes one variable for each export. Each query needs to be in a seperate sheet, but the same workbook and I need the sheets to have particular names. Normally when I export it gives the sheet the name of the query i.e. qryRequests, however, as it's the same query I'm using, and I don't want "qry" at the front, I'm unsure how to do this. The current export code I have is below, which would loop for each individual variable:

Code:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
        strcExportQuery, strFile

Many thanks for your help.
 
Never get tired of sharing this.
The built in transferspreadsheet doesn't have many options. It is kind of a one-size-fits all.
http://www.btabdevelopment.com/ts/default.aspx?PageId=49
When calling this function, pass in the Table or SQL Query name as the first argument and the Sheet name as the second argument.
The STRPATH - put the path inside the quotes "C:\MyExcelReports" - the path must exist.

Your code module in Tools- Reference must choose the Microsoft Excel (version) and a reference to DAO installed on the computer running this code.

This should get you started. There are countless options once this method is used.
 
Thanks RX, but this requires the workbook and sheet to exist already, I need to create the file, and then each sheet, as well as ensuring that the default sheets "Sheet 1/2/3" do not exist.

Thanks.
 
I ended up using 3 modules, one to create the file, one to export the data, and one to delete the extra sheets. This means I can now loop the 2nd module for each export, and then finish it by deleting the extra worksheets. I used a couple of other sources when going some googling.

The code probably looks ugly to a lot of people better minded than myself, but it works. Each Function also returns a boolean, to ensure it was successful, as the next one would fail otherwise. This is what I've got if anyone wants to make use or make amendments:
Code:
Option Compare Database

    Public Function CreateTQExcelWB(strWBName As String) As Boolean

    On Error GoTo err_handler
    CreateTQExcelWB = True
    strWBName = "H:\TRS\" & strWBName

    Set appExcel = Excel.Application

    If Dir(strWBName & ".xls") <> "" Then
        SetAttr strWBName & ".xls", vbNormal
        Kill strWBName & ".xls"
    End If
    
    Set Wbk = appExcel.Workbooks.Add
    ' **** save the new workbook with the strWBName path/filename
    Wbk.SaveAs strWBName
    
    Set wks = Wbk.Worksheets("Sheet1")
    
    Set wks = Nothing
    Wbk.Save
    Wbk.Close
    Set Wbk = Nothing

exit_routine:
    appExcel.Quit
    Set appExcel = Nothing
    Exit Function

err_handler:
    Dim Errorcode As Integer
    Errorcode = MsgBox("Error: " & Err.Description, vbOKCancel, "Error")
    If Errorcode = vbOK Then
        CreateTQExcelWB = False
        Resume exit_routine
    Else
        Resume
    End If



End Function

Public Function SendTQ2ExcelSheet(strTQName As String, strSheetName As String, strPath As String) As Boolean

' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to send it to

    Dim rst As DAO.Recordset
    Dim ApXL As Object
    Dim xlWBk As Object
    Dim xlWSh As Object
    Dim fld As DAO.Field
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107

    SendTQ2ExcelSheet = True
   
    On Error GoTo err_handle

    Set rst = CurrentDb.OpenRecordset(strTQName)
    Set ApXL = CreateObject("Excel.Application")
    Set xlWBk = ApXL.Workbooks.Open(strPath)

    ApXL.Visible = True

    Set xlWSh = xlWBk.Worksheets.Add
    
    xlWSh.Name = strSheetName

    xlWSh.Activate
    xlWSh.Range("A1").Select

 

    For Each fld In rst.Fields
        ApXL.ActiveCell = fld.Name
        ApXL.ActiveCell.Offset(0, 1).Select
    Next

    rst.MoveFirst
    xlWSh.Range("A2").CopyFromRecordset rst
    xlWSh.Range("1:1").Select

    With ApXL.Selection.Font
        .Name = "Arial"
        .Size = 12
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
    End With

    ApXL.Selection.Font.Bold = True

    With ApXL.Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .MergeCells = False
    End With

    ' selects all of the cells
    ApXL.ActiveSheet.Cells.Select

    ' does the "autofit" for all columns
    ApXL.ActiveSheet.Cells.EntireColumn.AutoFit

    ' selects the first cell to unselect all cells
    xlWSh.Range("A1").Select

    rst.Close
    Set rst = Nothing
    
    xlWBk.Save
    xlWBk.Close
    
    ApXL.Quit

Exit Function

err_handle:

    DoCmd.SetWarnings True
    MsgBox Err.Description, vbExclamation, Err.Number
    SendTQ2ExcelSheet = False
    ApXL.DisplayAlerts = False
    ApXL.Quit
    Exit Function

End Function

Public Function DeleteTQExcelWBk(strPath As String) As Boolean

    On Error GoTo err_Handling
    
    Dim appExcel As Object
    Dim Wbk As Object
    Dim WSh As Object
    
    DeleteTQExcelWBk = True
    
    Set appExcel = Excel.Application
    Set Wbk = appExcel.Workbooks.Open(strPath)
    
    
    appExcel.Visible = True
    appExcel.DisplayAlerts = False
    appExcel.Sheets("Sheet1").Select
    appExcel.ActiveSheet.Delete
    appExcel.Sheets("Sheet3").Select
    appExcel.ActiveSheet.Delete
    appExcel.Sheets("Sheet2").Select
    appExcel.ActiveSheet.Delete
    
    Wbk.Save
    Wbk.Close
    
    appExcel.Quit
    
    Exit Function

err_Handling:

    DoCmd.SetWarnings True
    MsgBox Err.Description, vbExclamation, Err.Number
    DeleteTQExcelWBk = False
    appExcel.DisplayAlerts = False
    appExcel.Quit
    Exit Function
    
End Function
 
Sorry about the folder / workbook creation. It was a busy day, glad you got it.

On my Excel Reports, I always start the header on Row 5, data on row 6
The top is reserved to programically add formulas and titles.
If you want the titles in the header, here is some code to review.
This puts the data in row 6, then steps back up and adds the Query headers into the row above.
While you have a Recordset - it never hurts to record the number of records. My preference is to select the first column/row to the last column/row and put the gridmarks that give it the customer approved appearance.

Code:
620   On Error GoTo PROC_Error
630     ObjXL.Visible = False                                                              ' ******* change for production
640   intRowPos = 6                                                                                 ' Sets starting Row for data in Excel - reference fields to this
650   DoEvents
660   ObjXL.DisplayAlerts = False                                                       ' Turn off Display Alerts
670   ObjXL.Worksheets(intWorksheetNum).Cells(intRowPos, 1).CopyFromRecordset objRS
680   DoEvents
690   intMaxRecordCount = objRS.RecordCount - 1                                                      ' - use for max rows returned in formatting later
           'Debug.Print "max record count is " & intMaxRecordCount
                                                  ' ------- Create Header in new Excel based on Query
700       intMaxheaderColCount = objRS.Fields.count - 1
710       For intHeaderColCount = 0 To intMaxheaderColCount
720     If Left(objRS.Fields(intMaxheaderColCount).Name, 3) <> "xxx" Then  ' Future use - adding xxx in cross tab queries for fields to exclude
730         ObjXL.Worksheets(intWorksheetNum).Cells(intRowPos - 1, intHeaderColCount + 1) = objRS.Fields(intHeaderColCount).Name    ' Relative to intRowPos
740     End If
750       Next intHeaderColCount
          'Debug.Print "Columns created count is " & intHeaderColCount
760       ObjXL.Rows((intRowPos - 1) & ":" & (intRowPos - 1)).Select                                    ' Selection for Bold header column (can make 2 if needed)
 

Users who are viewing this thread

Back
Top Bottom