简体   繁体   English

在Excel中使用vba将Access查询的结果输出到Excel电子表格中的问题

[英]Issues with outputting results of an Access query into an Excel spreadsheet using vba in Excel

I am having problems with some code that is supposed to take the results of an Access query and place it in an Excel spreadsheet. 我遇到了一些应该采用Access查询结果并将其放在Excel电子表格中的代码的问题。 I am trying to do this from an Excel VBA module. 我正在尝试从Excel VBA模块执行此操作。 Here is the code I have so far. 这是我到目前为止的代码。

Sub dbopen()

Dim objAccess As Object
Dim db, qr, wb As String
Dim WSS As Worksheet

Set WSS = ActiveSheet
Set objAccess = CreateObject("Access.Application")

db = "C:\Program Files\BWCApps\Databases\DEP\DEP SQL.mdb"
qr = "Active List of Doctors No Duplicates"
wb = "TEMP UNZIP\DEP List of Doctors " & Format(Date, "mm-dd-yyyy") & ".xls"

' Get results of Active List query and put in Excel worksheet
If Not objAccess Is Nothing Then
    With objAccess
        .OpenCurrentDatabase db
        .docmd.OpenQuery qr
        .docmd.OutputTo acOutputQuery, qr, acFormatXLS, "C:\Users\A78853\Desktop\" & wb, True
        .CloseCurrentDatabase
        .Quit
    End With
End If

End Sub

The code actually puts the results into the worksheet but then hangs without stopping. 该代码实际上将结果放入工作表中,然后挂起而不停止。 When I force a stop I get the following error message. 当我强制停止时,出现以下错误消息。

"Run-time error '-2147023170 (800706be)': Automation error The remote procedure call failed." “运行时错误'-2147023170(800706be)':自动化错误远程过程调用失败。”

I'm at a complete loss as to what is happening here, so any help would be greatly appreciated! 我对这里发生的事情完全不知所措,因此我们将不胜感激! Thank you! 谢谢!

See Remou's comment first and see if that helps. 请先查看Remou的评论,看看是否有帮助。 If you get completely stuck and decide to start from Access and export to Excel: 如果您完全陷入困境并决定从Access开始并导出到Excel:

Here is some sample code to export a query from Access VBA to Excel: 以下是一些示例代码,可将查询从Access VBA导出到Excel:

Dim outputFileName As String

       outputFileName = CurrentProject.Path & "\WhereYouWantItExported" & Format(Date, "yyyyMMdd") & ".xls"
            DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "YourQueryName", outputFileName, True

       MsgBox "Data exported to  " & CurrentProject.Path & "\Reports\WhereYouWantIt_" & Format(Date, "yyyyMMdd") & ".xlsx"

You should be able to add this to an On Click handler or something and export what you need. 您应该能够将此添加到“单击时”处理程序或其他内容中,然后导出所需的内容。 Of course, this is for Access to Excel, not Excel to Access back to Excel. 当然,这是用于访问Excel,而不是用于Excel返回到Excel。

In case you needed it, here it is. 如果您需要它,就在这里。 I realize this doesn't exactly answer your question because the process originates in Access and not Excel. 我意识到这不能完全回答您的问题,因为该过程起源于Access而不是Excel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM