获取已打开的 Excel 实例的句柄,并从 Outlook 运行内部的宏



这不是以下内容的副本:是否可以将 Excel 应用程序对象设置为指向已打开的 Excel 实例?

这个想法是执行已从Outlook打开的Excel实例中包含的VBA子

我正在将 VBA 子作为 Outlook 中规则的一部分运行。

这是我的代码:

On Error Resume Next
        Dim tPath As String
        tPath = "X:LucasLucasSheet.xlsm"
        Dim exApp As New Excel.Application
        Dim wb As Excel.Workbook
        wb = System.Runtime.InteropServices.Marshal.BindToMoniker(tPath)
不幸的是,在

这一点上,在调试模式下运行时,我可以看到 wb 等于 Nothing

        Set exApp = wb.Parent
        usedSub = "PrintSingle"
        exApp.Run usedSub            
        wb.Close False

是否可以使此代码在 Outlook 2010 中工作?

而不是在代码中创建新的 Excel 应用程序:

 Dim exApp As New Excel.Application

您需要获取正在运行的 Excel 实例:

exApp =  System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

有关详细信息和 VB.NET 中的示例代码,请参阅在 VB 中访问正在运行的 Excel 实例。

使用应用程序类的 Run 方法以编程方式运行 VBA 宏。

首先,您需要一个将附加到正在运行的 Excel 实例的函数,然后按名称查找工作簿。

'@Description "Return the open Excel workbook"
Public Function GetHandleForExistingWorkbook(ByVal fullPath As String) As Object
    On Error GoTo openExcel
    
    Dim excelApp As Object
    Set excelApp = GetObject(, "Excel.Application")
    
    Dim wb As Object
    For Each wb In excelApp.Workbooks
        If wb.FullName Like fullPath & "*" Then
            Set GetHandleForExistingWorkbook = wb
            Exit For
        End If
    Next wb
    Exit Function
    
openExcel:
    If Err.Number = 429 Then
        ' Open it if it wasn't already open
        Set excelApp = CreateObject("Excel.Application")
        GetHandleForExistingWorkbook = excelApp.Workbooks.Open(fullPath)
    Else
        Debug.Print "Unhandled exception: " & Err.Number & " " & Err.Description
    End If
End Function

一旦您知道自己在正确的位置,就可以通过调用 Excel 应用程序对象来运行宏:

Public Sub RunMacroInOpenWorkbook(ByVal fullPath As String, ByVal macroName As String, _
Optional ByVal macroParameters As String = "")
    Dim theWorkBook As Object
    Set theWorkBook = GetHandleForExistingWorkbook(fullPath)
    theWorkBook.Application.Run "'" & theWorkBook.Name & "'!" & macroName, macroParameters
    theWorkBook.Close False
End Sub

然后,使用它的代码将如下所示:


    Dim tPath As String
    tPath = "X:LucasLucasSheet.xlsm"
    usedSub = "PrintSingle"
    RunMacroInOpenWorkbook tPath, usedSub   

使用 Application.Run 命令时需要包含工作簿名称。

尝试使用这个:

    exApp.Run wb.Name & "!" & usedSub ' must include workbook name

相关内容

最新更新