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

1 Answers1

0

Without knowing the exception it's hard to diagnose. I recommend one of these standard methodologies to call .NET code from VBA:

  1. Create a COM-visible .NET DLL, add a reference to it in VBA, then instantiate your "Word" class from VBA. See this question and this blog post.
  2. Use VSTO.
Community
  • 1
  • 1
mr_plum
  • 2,448
  • 1
  • 18
  • 31