views:

76

answers:

1

Hi, this is probably something I should know, but I'm puzzled by this. I'm trying to create some objects and being able to access and modify these globally.

I tried to create a Public Module and declare a few objects in this. I am able to access these from another sub, but I get an exception error when after building and runing the process and trying to modify these object.

The same thing happens if I declare the object in the Public Class Form1. For example like this:

Public Class Form1
Public appWord = New Microsoft.Office.Interop.Word.Application
Public wordDoc as Microsoft.Office.Interop.Word.Document

Now, in my button, I've got this:

wordDoc = appWord.Documents.Open("c:\temp\test.dot")
appWord.Quit()
appword = Nothing

After I've built the project and press the button, I get this error:

Type mismatch. (Exception from HRESULT: 0x80020005(DISP_E_TYPEMISMATCH))

What I'm trying to do is to start a Winword.exe and then load a template in that and read some macros from the template. Then I want to be able to replace the macrocode from my application and then store the changes to the macro. And I've got a Public sub which reads the macro and puts the text in a textbox. And then I've got a separate Public Sub which does the replacement. However, I'm trying to figure out a clever way of creating these objects one time so I don't have to do it over and over again.

Edit: This doesn't happen if I declare the object in the same sub as the button, like this:

Private sub Button1_Click
Dim appWord = New Microsoft.Office.Interop.Word.Application
Dim wordDoc as Microsoft.Office.Interop.Word.Document

wordDoc = appWord.Documents.Open("C:\temp\test.dot")
appWord.Quit()
End sub

Edit: I got it working now. There wasn't an error, it was just that the document didn't exist.. I'm an idiot :)

+1  A: 

The problem you're getting has nothing to do with the way you declare your "globals". It's a Dispatch interface error telling you the type you're passing is not what the interop class is expecting, that is, the call to Open is probably wrong. According to this reference it should be passed by reference (so a literal string is not valid).

Jorge Córdoba
But why is it working when I declare these objects in the same sub as the one I modify it in? See my edited first post for details.
Kenny Bones
Sorry, I'm an idiot.. The document doesn't exist..Thanx for clearing this up! There you see how a human typo can ruin everything! :)
Kenny Bones
We keep learning only till we think "I'm an Idiot". When we think we are genious - the progress stops!!
MSIL