Using Office functions question - type mismatch error

  • Thread starter Thread starter herman404
  • Start date Start date
H

herman404

Hi everyone, I am trying to write a function that will be called from
another function. It will do a save as on a word document, and the
document name will be passed via a parameter. I keep getting a Type
Mismatch error on the Documents.Open call below, but it works fine when
I specify the name of the file in the Open call. How come it doesn't
work with the parameter, even when I declare a local variable and set
it equal to the parameter? The parameter is confirmed as being a
string using vartype.


Function ConvertWordFile(Filename)
Const wdFormatText = 2
Dim fname
Dim objWord
Dim objDoc

Set fname = Filename
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(fname)

objWord.Visible = FALSE

objDoc.SaveAs Filename+".txt", wdFormatText

objWord.Quit
End function
 
The caller is expecting an "Object", whereas you are passing a String.
Don't ask me why it won't work, but rest assured if you cast the string to
an Object, it'll be okay, such as:


objDoc = objWord.Documents.Open(FileName:=CType(fname, Object))


Remember to "Release" these interfaces when you are done with them,
preferably in an exception handler "Finally" statement.
 
herman404 said:
Hi everyone, I am trying to write a function that will be called from
another function. It will do a save as on a word document, and the
document name will be passed via a parameter. I keep getting a Type
Mismatch error on the Documents.Open call below, but it works fine when
I specify the name of the file in the Open call. How come it doesn't
work with the parameter, even when I declare a local variable and set
it equal to the parameter? The parameter is confirmed as being a
string using vartype.


Function ConvertWordFile(Filename)
Const wdFormatText = 2
Dim fname
Dim objWord
Dim objDoc

Set fname = Filename
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(fname)

objWord.Visible = FALSE

objDoc.SaveAs Filename+".txt", wdFormatText

objWord.Quit
End function

IS this a VB6 App ?
Jens
 
Hi Fred, thanks for the tip, that makes sense. However, I am getting
syntax errors on the casting, and I can't figure out what's wrong (I am
new to VB, by the way, as I usually write in Java and C#) It returns a
syntax error on the CType call, saying that the object type is not
recgonised. The CObj data type does not work either. A search on
another page mentioned calling CType with a variable of the type rather
than the name of the type. But when I try to do a:

Dim obj As Object

The interpreter marks a syntax error on the As! Is there any way to do
this, or should I just give up and write this in C#?
 
It sounds like you are writing this in VBA and not VB.Net. I don't
think VBA supports the As clause and it certainly does not support
CType.
 
Back
Top