MS Access - > Excel MsgBox出现两次

时间:2017-07-12 13:58:04

标签: excel vba excel-vba access-vba

我正在Access 2016中编写一个模块,用于打开Excel电子表格,将数据复制到Excel表格中,然后运行存储在显示消息框的Excel文件中的子文件,然后生成图表(或者至少应该生成图表) !)。

这是访问代码:

Option Compare Database
Option Explicit

Sub QueryExportMod()

'variable initilizations and definitions ---------------------------------------------------------------------------------------



Dim db As DAO.Database
Set db = CurrentDb

Dim totalFindingsQuery As String
Dim breakdownFindingsQuery As String
totalFindingsQuery = 'SQL text
breakdownFindingsQuery = 'SQL text

Dim tempQ1 As DAO.QueryDef
Dim tempQ2 As DAO.QueryDef
Set tempQ1 = db.CreateQueryDef("tempQ1", totalFindingsQuery)
Set tempQ2 = db.CreateQueryDef("tempQ2", breakdownFindingsQuery)

Dim rs1 As Recordset
Dim rs2 As Recordset
Set rs1 = db.OpenRecordset("tempQ1")
Set rs2 = db.OpenRecordset("tempQ2")

Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Set xlApp = New Excel.Application
Set wb = xlApp.Workbooks.Open(CurrentProject.Path & "\ExportExcelTest.xlsm")
Set ws = wb.Worksheets("Sheet1")

Dim table As ListObject
Set table = ws.ListObjects("Table1")



'Modifying files and data ------------------------------------------------------------------------------------------------------


ws.ListObjects("Table1").DataBodyRange.Rows.Delete

ws.Range("A2") = "Total Findings"
ws.Range("B2").CopyFromRecordset rs1
ws.Range("A3").CopyFromRecordset rs2

'Call autoGraph, the Excel sub
xlApp.Run "autoGraph()"

xlApp.Visible = True

Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing

DoCmd.DeleteObject acQuery, "tempQ1"
DoCmd.DeleteObject acQuery, "tempQ2"

End Sub

'to be able to run the sub from a macro
Function KGQueryExportCall()
Call QueryExportMod
End Function

这是Excel子:

Sub autoGraph()

'AppActivate Application.Caption
MsgBox " <message> "

Dim tb1Range As Range
Set tb1Range = ActiveSheet.Range("Table1")

Range("Table1").Select
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Table1")


End Sub

当我运行Access子QueryExportMod时,会生成消息框(我遇到的另一个问题是它总是在其他窗口后面。有人知道如何强制它到当前窗口,顶部的那个?我尝试了AppActivate Application.Caption,但它破坏了我的代码),当我在消息框中按“确定”时,同样的确切消息框将重新出现。一旦我在这个副本上按“确定”,那么Excel电子表格将打开,其他一切正常。我该怎样摆脱这个副本?

感谢您的帮助

编辑:我在Excel子目录中添加了两个DeBug行,如下所示:

DeBug.Print("1")
MsgBox " <message> "
DeBug.Print("2")

并最终获得

1 2 1 2在即时窗口当我运行Access模块​​时,所以我现在知道Excel sub正在运行两次,但我仍然无法弄清楚导致它的原因是什么去做。当我从Excel内部运行Excel模块时,我只能

1 2

我认为这可能与实际申请开放两次有关?当我没有消息框行的情况下运行时,我看到一个口吃,就像一个窗口打开然后几乎立即关闭,然后再次重新打开

1 个答案:

答案 0 :(得分:2)

您不应在此处添加括号:

xlApp.Run "autoGraph()"

在Access中,当您使用Application.Run添加括号时,它只会生成运行时错误,在Excel中它显然会运行两次。

删除它们,它将被修复。