Excel VBA运行和导出访问查询

我有以下代码从Excel启动Access数据库中的一系列查询。 当这些查询在Access中自行运行时,它们工作正常并成功生成正确的文件,但是当我使用button单击将macros转换为在Excel中运行时,遇到了一些问题。 看到我的代码如下:

Sub AccessImport() Dim acApp As Object Dim MyDatabase As String Dim question As String question = MsgBox(Prompt:="Are you sure you want to complete this action? Running this process is lengthy and could take a couple minutes to complete.", Buttons:=vbYesNo, Title:="Run SOD Matrix") If question = vbYes Then MyDatabase = "directory string" OutputFile = "output string" 'open the database and apend the combination table to existing Set acApp = CreateObject("Access.Application") acApp.OpenCurrentDatabase (MyDatabase) acApp.Visible = True acApp.UserControl = True acApp.DoCmd.SetWarnings False acApp.DoCmd.OpenQuery "QRYDELETE_PS_ROLE_NAMES", acViewNormal, acEdit acApp.DoCmd.OpenQuery "QRYDELETE_PS_ROLE_USER", acViewNormal, acEdit acApp.DoCmd.OpenQuery "QRYDELETE_SOD_TBL", acViewNormal, acEdit acApp.DoCmd.OpenQuery "QRYAPPEND_PS_ROLE_NAMES", acViewNormal, acEdit acApp.DoCmd.OpenQuery "QRYAPPEND_PS_ROLE_USER", acViewNormal, acEdit acApp.DoCmd.OpenQuery "QRYAPPEND_SOD_TBL", acViewNormal, acEdit 'acApp.DoCmd.OpenQuery "QRY_HIGH", acViewNormal, acEdit acApp.DoCmd.OutputTo acOutputQuery, "QRY_HIGH", "ExcelWorkbook(*.xlsx)", OutputFile, _ False, "", , acExportQualityPrint acApp.DoCmd.SetWarnings True acApp.CloseCurrentDatabase acApp.Quit Set acApp = Nothing Else MsgBox ("Process has been cancelled.") Exit Sub End If MsgBox ("Process has completed successfully.") End Sub 

对于最后一个查询,意图导出并保存输出,我遇到了一个错误,告诉我Property is not found. 我已经尝试将DoCmd更改为TransferSpreadsheetacFormalXLS的格式types以防止转换问题,但仍然无法成功完成。 我是否需要将此代码放在模块中,而不是放在工作表上? 想法/帮助?

Siddharth在这个声明中指出了这个问题:

 acApp.DoCmd.OutputTo acOutputQuery, "QRY_HIGH", "ExcelWorkbook(*.xlsx)", OutputFile, _ False, "", , acExportQualityPrint 

如果没有对Access对象库的引用,Excel将对Access常量acOutputQueryacExportQualityPrint

Option Explict添加到模块的声明部分,然后从VB编辑器的主菜单中运行Debug-> Compile是明智的。 当你这样做,我怀疑你会发现类似的问题,像这样的线…

 acApp.DoCmd.OpenQuery "QRYDELETE_PS_ROLE_NAMES", acViewNormal, acEdit 

Excel也不了解Access常量acViewNormalacEdit 。 但是,如果你的意图是执行“动作”查询( INSERTUPDATEDELETE等),这些常量是无法识别的。 否则,您将在devise视图中打开这些查询,而不是执行它们。

考虑一个不同的方法…

 Const dbFailOnError As Long = 128 'acApp.DoCmd.SetWarnings False ' leave SetWarnings on! acApp.CurrentDb.Execute "QRYDELETE_PS_ROLE_NAMES", dbFailOnError acApp.CurrentDb.Execute "QRYDELETE_PS_ROLE_USER", dbFailOnError