1

I've got some VB.net code and a custom Microsoft Word VBA macro. I'm trying to pass the VB.net instance into the macro so that i can run a function on that object from the macro. I can't seem to pass in the object from the VB.net code to the Macro.

Warning, i'm brand new to VB and the Word marcos. Thanks for any and all help!

C#.net code i use to create the word doc and pass it to the VB.net code

 private void BtnStartWord_Click(object sender, EventArgs e)
    {

        Microsoft.Office.Interop.Word.Application wdApp = new Microsoft.Office.Interop.Word.Application();
        wdApp.Documents.Add(@"C:\template.dotm");
        wdApp.Visible = true;

        VBWord.Word wordVB = new VBWord.Word();

        wordVB.Connect(Handle.ToInt32(), wdApp);
    }

VB.net code

Public Class Word
    Public Sub Connect(ByVal plWinHandle As Long, _
                       ByVal pobjDocHandle As Object)

        RunMacro(pobjDocHandle, New Object() {"Connect", plWinHandle, Me})
    End Sub
    Private Sub RunMacro(ByVal oApp As Object, ByVal oRunArgs() As Object)
        oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default Or System.Reflection.BindingFlags.InvokeMethod, Nothing, oApp, oRunArgs)
    End Sub
End Class

And, inside of my Word template, i have some code. The code is inside of TemplateProjects -> Microsoft Word Objects -> ThisDocument and is as follows.

Option Explicit

Public Sub Connect(ByVal plWindow As Long, ByRef pobjControl As Object)
    Set goApp.App = Word.Application
    goApp.WindowHandle = plWindow
    goApp.ControlHandle = pobjControl
End Sub

With the above goApp defined in Modules -> Globals

Option Explicit
Public goApp As New WordApp

Currently, the VB code is throwing an error on the oApp.GetType().InvokeMember line above. I don't think it likes the argument of Me being passed into it. But, i don't know how to pass in itself.

The Error that gets thrown is

Message = "Exception has been thrown by the target of an invocation."
InnerException = {"Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"}

And, what i ultimately want to be able to do is a macro in Word to call back a function in the VB code. Something like the following.

Sub ApproveButton(ByVal control As IRibbonControl)
    '-----------------------------------------------------------------------------
    ' Description: This procedure sends the Approve action request back to the VB code
    '-----------------------------------------------------------------------------
    goApp.SendAction "Approve"
End Sub
4

1 回答 1

0

在不知道异常的情况下很难诊断。我推荐使用以下标准方法之一从 VBA 调用 .NET 代码:

  1. 创建一个 COM 可见的 .NET DLL,在 VBA 中添加对它的引用,然后从 VBA 实例化您的“Word”类。请参阅此问题此博客文章
  2. 使用VSTO
于 2013-10-17T17:52:11.520 回答