Formatting outputted Excel files from Access using VBA?

后端 未结 4 633
面向向阳花
面向向阳花 2021-01-03 17:01

Here I have some VBA code that outputs a ton of files into Excel files. My question is, from this, is there anyway for it to Format the excel file a bit? What I would like t

4条回答
  •  孤城傲影
    2021-01-03 17:18

    I have come across this problem a couple of times as well. As @Remou said, you will need to open excel to format xls files, this modification of your code silently opens Excel and that should get you in the right direction. Remember to add a reference to the Microsoft Excel Object Library in your VBA project.

    Sub OutPutXL()
    Dim qdf As QueryDef
    Dim rs As DAO.Recordset
    Dim xl as Excel.Application
    Dim wb as Object
    Dim strFile as string
    
    Set qdf = CurrentDb.QueryDefs("OutputStudents")
    Set rs = CurrentDb.OpenRecordset("Teachers")
    Set xl = New Excel.Application
    xl.DisplayAlerts = False
    
    Do While Not rs.EOF
        qdf.SQL = "SELECT * FROM Students WHERE contact='" & rs!contact & "'"
    
        'Output to Excel
        strFile = "C:\Users\chrisjones\Documents\ProjectionsFY14\Teachers\" & rs!contact & ".xls"
        DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, qdf.Name, strFile, True
    
        'Start formatting'
        Set wb = xl.Workbooks.Open(strFile)
        With wb.Sheets(qdf.name)
            'Starting with a blank excel file, turn on the record macro function'
            'Format away to hearts delight and save macro'
            'Past code here and resolve references'
        End With
        wb.save
        wb.close
        set wb = Nothing
        rs.MoveNext
    Loop
    xl.quit
    set xl = Nothing
    End Sub
    

提交回复
热议问题