Export Form Datasheet Results To Excel Spreadsheet

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • icenemesis
    New Member
    • Jul 2007
    • 13

    Export Form Datasheet Results To Excel Spreadsheet

    I have a form that searches dynamically based on what criteria the user enters. The resulting query populates a subform in datasheet view.

    If I wanted to have a button that would export the results of the query that is the source for that datasheet form to excel. How would I go about doing that through VBA?

    Thanks in advance.
  • icenemesis
    New Member
    • Jul 2007
    • 13

    #2
    I figured it out.

    Code:
    Dim oExcel As Object
       Dim oBook As Object
       Dim oSheet As Object
    
       'Start a new workbook in Excel
       Set oExcel = CreateObject("Excel.Application")
       Set oBook = oExcel.Workbooks.Add
    
       'Add data to cells of the first worksheet in the new workbook
       Set oSheet = oBook.Worksheets(1)
       oSheet.Range("A1").Value = "Doc #"
       oSheet.Range("B1").Value = "Document Name"
       oSheet.Range("C1").Value = "Revision"
       oSheet.Range("D1").Value = "Status"
       oSheet.Range("E1").Value = "Notes"
       oSheet.Range("A1:E1").Font.Bold = True
       
       Dim rs As Recordset
       Set rs = Me.subResults.Form.Recordset
       
       Dim iRow As Integer
       iRow = 2
       Dim iRows As Integer
       iRows = rs.RecordCount
       
       Do While iRow <= iRows
       
        oSheet.Range("A" & iRow).Value = rs.Fields(0)
        oSheet.Range("B" & iRow).Value = rs.Fields(1)
        oSheet.Range("C" & iRow).Value = rs.Fields(2)
        oSheet.Range("D" & iRow).Value = rs.Fields(3)
        oSheet.Range("E" & iRow).Value = rs.Fields(4)
       
        iRow = iRow + 1
        rs.MoveNext
       Loop
       
       rs.MoveFirst
    
       'Save the Workbook and Quit Excel
       Dim sSave As String
       Dim sTime As String
       sTime = Replace(Replace(Now(), ":", "-"), "/", "-")
       sSave = "QMD Search Export " & sTime & ".xls"
       oBook.SaveAs "Y:\" & sSave
       oExcel.Quit
       Dim result
       result = MsgBox("Excel Spreadsheet saved under your 'Y:\' as '" & sSave & "'", _
                vbOKOnly, "Export Successful")

    Comment

    Working...