Type mismatch error when using 'With' on variable declared 'As Object'

D

danforest

I wrote a Microsoft Word automation app in VB, which I am now porting
to VB script. My initial code looked like this, and works fine:

Dim o as Word.Application
Set o = New Word.Application

o.documents.add (....)
with o
.Selection.TypeText "blah"
end with

When I change the declaration to

Dim o as Object
Set o = CreateObject ("Word.Application")

The object appears to be created OK, but I get an error 13 type
mismatch on the line starting with '.Selection.TypeText...'

I've tried declaring 'o' with no type specifier, (as you would see in
VBScript), and get the same results. Also, if I declare 'o' as
'Word.Application', and use CreateObject, that works too, so it seems
to be the initial variable declaration causing the problem. Anyone know
what's wrong here? thanks.


Dan
 
J

Jay Freedman

Hi Dan,

The problem is that Object is too general (indeed, as general as it's
possible to get), and the Object type doesn't contain a .Selection
member. A Word.Application object is more specific, and it does
contain a .Selection member.

In a more strongly typed language such as C++ or C#, you could declare
an Object, instantiate it with a pointer to a Word.Application, and
then cast it to Application in order to use its .Selection. That isn't
possible in any VB dialect.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 
D

danforest

Thanks Jay.

The problem turned out to be two different behaviors by VB, depending
on how I declared the Word application variable. When using 'Dim o as
Word.Application', and assigning an undeclared variable in
'.Selection.TypeText n', all worked fine. When running the same code
using CreateObject to declare the variable, then I got the type
mismatch error. So that was my bad for not declaring the variable, but
interesting to note the different responses by VB.

Dan
 
J

Jay Freedman

Hi Dan,

In VB and VBA, an undeclared variable is implicitly declared as type
Variant. This is usually a bad idea, and it's easily avoided by including
the Option Explicit statement in every module -- see
http://word.mvps.org/FAQs/MacrosVBA/DeclareVariables.htm for the
explanation.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top