从access vba运行excel中的2个子程序 - 第一个运行,第二个不运行

问题描述 投票:0回答:2

我有一个 Access 数据库,可以调用 Excel 中的子程序并完美运行它。然后它会快速返回访问,提出一个问题,然后根据问题的答案,调用已打开的同一 Excel 电子表格中的第二个子程序。

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
2个回答
1
投票

呃,我一发帖就知道会发生这种事! 所以看起来错误实际上是在被调用的 Excel 子程序中。当我点击调试时,它仅突出显示正在调用 excel 子程序的访问行,但它是需要该对象的 excel 子程序。

保留这个,以防它对其他人有帮助,因为我花了很长时间试图解决我的访问问题,而不是我的 Excel 问题。


0
投票

从 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
© www.soinside.com 2019 - 2024. All rights reserved.