【问题标题】:Exporting Recordset to Spreadsheet将记录集导出到电子表格
【发布时间】:2013-04-26 12:08:55
【问题描述】:

刚刚开始掌握一些 VBA(这些东西对我来说是新的,所以请耐心等待!)

从查询 ContactDetails_SurveySoftOutcomes 中,我试图首先在该查询的 DeptName 字段中找到所有唯一值的列表,因此 rsGroup Dim 存储DeptName 字段上的分组查询。

然后,我将使用此分组列表作为再次循环执行相同查询的方式,但将每个唯一条目作为整个记录集的过滤器传递,并将每个过滤后的记录集导出到其自己的 Excel 电子表格...参见Do While Not 循环。

我的代码在DoCmd.TransferSpreadsheet ... rsExport 部分出错。我对此有点陌生,但我猜我的记录集的 Dim 名称 rsExport 在此方法中不被接受..?

是否可以轻松修复我已经开始的代码,或者我应该使用完全不同的方法来实现这一切?

代码

Public Sub ExportSoftOutcomes()

Dim rsGroup As DAO.Recordset
Dim Dept As String
Dim myPath As String

myPath = "C:\MyFolder\"

Set rsGroup = CurrentDb.OpenRecordset("SELECT ContactDetails_SurveySoftOutcomes.DeptName " _
& "FROM ContactDetails_SurveySoftOutcomes GROUP BY ContactDetails_SurveySoftOutcomes.DeptName", dbOpenDynaset)

Do While Not rsGroup.EOF

    Dept = rsGroup!DeptName

    Dim rsExport As DAO.Recordset
    Set rsExport = CurrentDb.OpenRecordset("SELECT * FROM ContactDetails_SurveySoftOutcomes " _
    & "WHERE (((ContactDetails_SurveySoftOutcomes.DeptName)='" & Dept & "'))", dbOpenDynaset)

    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, rsExport, myPath & Dept & "\" & Dept & " - Soft Outcomes Survey.xls", True

    rsGroup.MoveNext

Loop

End Sub

固定代码

Public Sub ExportSoftOutcomes()

Dim rsGroup As DAO.Recordset
Dim Dept As String
Dim myPath As String

myPath = "C:\MyFolder\"

Set rsGroup = CurrentDb.OpenRecordset("SELECT ContactDetails_SurveySoftOutcomes.DeptName " _
& "FROM ContactDetails_SurveySoftOutcomes GROUP BY ContactDetails_SurveySoftOutcomes.DeptName", dbOpenDynaset)

Do While Not rsGroup.EOF
    Dept = rsGroup!DeptName

    Dim rsExportSQL As String
    rsExportSQL = "SELECT * FROM ContactDetails_SurveySoftOutcomes " _
    & "WHERE (((ContactDetails_SurveySoftOutcomes.DeptName)='" & Dept & "'))"

    Dim rsExport As DAO.QueryDef
    Set rsExport = CurrentDb.CreateQueryDef("myExportQueryDef", rsExportSQL)

    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "myExportQueryDef", myPath & Dept & "\" & Dept & " - Soft Outcomes Survey.xls", True

    CurrentDb.QueryDefs.Delete rsExport.Name

    rsGroup.MoveNext
Loop

End Sub

【问题讨论】:

    标签: ms-access ms-access-2007 vba ms-access-2010


    【解决方案1】:

    你是对的,你的rsGroup 参数是错误的,Access 需要一个表名或选择查询。

    试试这个代码:

    strExport = "SELECT * FROM ContactDetails_SurveySoftOutcomes " _
    & "WHERE (((ContactDetails_SurveySoftOutcomes.DeptName)='" & Dept & "'))"
    
    Set qdfNew = CurrentDb.CreateQueryDef("myExportQueryDef", strExport)
    
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "myExportQueryDef", myPath & Dept & "\" & Dept & " - Soft Outcomes Survey.xls", True
    
    CurrentDb.QueryDefs.Delete qdfNew.Name 'cleanup
    

    希望有效

    【讨论】:

    • 它是说 Microsoft Access 数据库引擎找不到对象 然后将 SQL 字符串插入错误消息中,就好像它是我的对象的名称...错过了一步?
    【解决方案2】:

    试试这个希望对你有帮助

    Function Export2XLS(sQuery As String)
        Dim oExcel          As Object
        Dim oExcelWrkBk     As Object
        Dim oExcelWrSht     As Object
        Dim bExcelOpened    As Boolean
        Dim db              As DAO.Database
        Dim rs              As DAO.Recordset
        Dim iCols           As Integer
        Const xlCenter = -4108
    
        'Start Excel
        On Error Resume Next
        Set oExcel = GetObject(, "Excel.Application")    'Bind to existing instance of Excel
    
        If Err.Number <> 0 Then    'Could not get instance of Excel, so create a new one
            Err.Clear
            On Error GoTo Error_Handler
            Set oExcel = CreateObject("excel.application")
            bExcelOpened = False
        Else    'Excel was already running
            bExcelOpened = True
        End If
        On Error GoTo Error_Handler
        oExcel.ScreenUpdating = False
        oExcel.Visible = False   'Keep Excel hidden until we are done with our manipulation
        Set oExcelWrkBk = oExcel.Workbooks.Add()    'Start a new workbook
        Set oExcelWrSht = oExcelWrkBk.Sheets(1)
    
        'Open our SQL Statement, Table, Query
        Set db = CurrentDb
        Set rs = db.OpenRecordset(sQuery, dbOpenSnapshot)
        With rs
            If .RecordCount <> 0 Then
                'Build our Header
                For iCols = 0 To rs.Fields.Count - 1
                    oExcelWrSht.Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
                Next
                With oExcelWrSht.Range(oExcelWrSht.Cells(1, 1), _
                                       oExcelWrSht.Cells(1, rs.Fields.Count))
                    .Font.Bold = True
                    .Font.ColorIndex = 2
                    .Interior.ColorIndex = 1
                    .HorizontalAlignment = xlCenter
                End With
                oExcelWrSht.Range(oExcelWrSht.Cells(1, 1), _
                                  oExcelWrSht.Cells(1, rs.Fields.Count)).Columns.AutoFit    'Resize our Columns based on the headings
                'Copy the data from our query into Excel
                oExcelWrSht.Range("A2").CopyFromRecordset rs
                oExcelWrSht.Range("A1").Select  'Return to the top of the page
            Else
                MsgBox "There are no records returned by the specified queries/SQL statement.", vbCritical + vbOKOnly, "No data to generate an Excel spreadsheet with"
                GoTo Error_Handler_Exit
            End If
        End With
    
        '    oExcelWrkBk.Close True, sFileName 'Save and close the generated workbook
    
        '    'Close excel if is wasn't originally running
        '    If bExcelOpened = False Then
        '        oExcel.Quit
        '    End If
    
    Error_Handler_Exit:
        On Error Resume Next
        oExcel.Visible = True   'Make excel visible to the user
        rs.Close
        Set rs = Nothing
        Set db = Nothing
        Set oExcelWrSht = Nothing
        Set oExcelWrkBk = Nothing
        oExcel.ScreenUpdating = True
        Set oExcel = Nothing
        Exit Function
    
    Error_Handler:
        MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
               "Error Number: " & Err.Number & vbCrLf & _
               "Error Source: Export2XLS" & vbCrLf & _
               "Error Description: " & Err.Description _
               , vbOKOnly + vbCritical, "An Error has Occured!"
        Resume Error_Handler_Exit
    End Function
    

    【讨论】:

    • 谢谢你,尽管我在大约 2 年前得到的答案是可以接受的。
    • 这就是我要找的。我不喜欢创建查询,然后将其删除。这是不必要的。
    【解决方案3】:

    DoCmd.TransferSpreadsheet 期望它的第三个参数是一个字符串(变量或文字),指定表或查询的名称。因此,您可以使用相同的 SQL 代码创建一个名为“forExportToExcel”之类的 DAO.QueryDef,而不是打开 DAO.Recordset,然后在 TransferSpreadsheet 调用中使用该名称。

    【讨论】:

    • 我做了Dim rsExport As DAO.QueryDef,然后是Set rsExport = CurrentDb.CreateQueryDef("my SQL string"),然后在TransferSpreadsheet方法的第三个参数中引用了rsExport。错误消息引用我的 SQL 字符串说它不是一个有效的名称...
    • 我想我可以看到我在你的@Gord-Thompson 上犯的错误...需要先存储 SQL 字符串,然后将该 SQL 带入CreateQueryDef,其中第一个参数我可以给出可以在TransferSpreadsheet 方法中使用的查询的名称。还是谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多