【问题标题】:Running 2 subs in excel from access vba - first runs, second doesn't从 access vba 在 excel 中运行 2 个子程序-第一次运行,第二次不运行
【发布时间】:2022-11-26 01:41:09
【问题描述】:
所以我对这里的问题完全不知所措,而且有一次在这里找不到答案。
我有一个访问数据库,它在 excel 中调用一个 sub 并完美运行它。
然后它会弹回访问,提出一个问题,然后,根据问题的答案,应该在已经打开的同一个 excel 电子表格中调用第二个 sub。
excel 中的两个子项都是“公开的”,都位于“thisworkbook”下,我肯定知道第二个子项的名称是正确的。
访问代码如下。 (xlApp 之前由
Set xlApp = CreateObject("Excel.Application")
当我点击第二个 .run MacroName 行时,出现运行时错误 424“需要对象”。
谢谢
With xlApp
.Visible = True
.Workbooks.Open progsPathName & "excel_for_plots.xlsm"
MacroName = .ActiveWorkbook.Name & "!" & "ThisWorkbook.do_the_country_stuff"
.Run MacroName
' check the labels
m = MsgBox("Are the labels ok?", vbYesNo, "Label positions")
If m = vbNo Then
MacroName = .ActiveWorkbook.Name & "!" & "ThisWorkbook.first_check"
.Run MacroName
End If
End With
我试过检查子名称,检查它们是公共的,调用不同的子名称,使用即时窗口检查 2 个 MacroName 字符串是否相同,除了子名称。总是得到同样的错误:(
【问题讨论】:
标签:
excel
vba
ms-access
runtime-error
method-call
【解决方案1】:
呃,我一发帖就知道会发生这种情况!
所以看起来错误实际上是在被调用的 excel sub 中。当我点击调试时,它只突出显示了调用 excel sub 的访问行,但正是 excel sub 需要该对象。
保留它以防它帮助其他人,因为我花了很长时间试图找出我的访问问题是什么,而不是我的 excel 问题。
【解决方案2】:
从 Access 打开 Excel
- 这里只是一些想法(提示)。我看不到您的其余代码,所以也许您已经考虑了其中的一些。
Option Compare Database
Option Explicit
Sub DoTheExcel()
Const ProcName As String = "DoTheExcel"
' Use an error-handling routine!
On Error GoTo ClearError
' Which is it?
' Late-Bound
Dim xlApp As Object: Set xlApp = CreateObject("Excel.Application")
' Early-Bound: Tools->References->Microsof Excel 16.0 Object Library
'Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
' Use a workbook variable!
Dim wb As Object ' late binding
'Dim wb As Excel.Workbook ' early binding
Dim MacroName As String
Dim m As Long
' Use a boolean to see if it was successful!
Dim IsSuccess As Boolean
With xlApp
.Visible = True ' out-comment when done testing
Set wb = .Workbooks.Open(progsPathName & "excel_for_plots.xlsm")
MacroName = "'" & wb.Name & "'!" & "ThisWorkbook.do_the_country_stuff"
.Run MacroName
' check the labels
m = MsgBox("Are the labels ok?", vbYesNo, "Label positions")
If m = vbNo Then
MacroName = "'" & wb.Name & "'!" & "ThisWorkbook.first_check"
.Run MacroName
End If
IsSuccess = True
End With
ProcExit:
On Error Resume Next
' Save and close the workbook.
If Not wb Is Nothing Then
wb.Close SaveChanges:=IIf(IsSuccess, True, False)
End If
' Quit the instance of Excel.
If Not xlApp Is Nothing Then xlApp.Quit
On Error GoTo 0
Exit Sub
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Sub