Checking for file type programmatically

A

Angie

I have a program that looks for RTF files. Sometimes though it throws and
error because someone just renamed there file from a .doc to a .rtf. I need
to make sure that the file type is Rich Text, not just count on the file
extension. Is there a VBA line for this? I thought ActiveDocument.Type might
work, but it gives me a 0, not sure if this is boolean or not. Thanks all
 
J

Jay Freedman

Angie said:
I have a program that looks for RTF files. Sometimes though it throws
and error because someone just renamed there file from a .doc to a
.rtf. I need to make sure that the file type is Rich Text, not just
count on the file extension. Is there a VBA line for this? I thought
ActiveDocument.Type might work, but it gives me a 0, not sure if this
is boolean or not. Thanks all

You can open the file as if it were a pure text file and check the first six
characters. If it's a real RTF file, those characters will be "{\rtf1".

Sub demo()
Dim dlg As Dialog
Dim msg As String

Set dlg = Dialogs(wdDialogFileOpen)
With dlg
If .Display = -1 Then
msg = .Name & " is"
If Not IsRtf(WordBasic.filenameinfo$(.Name, 1)) Then
msg = msg & " not"
End If
msg = msg & " a real RTF file"
MsgBox msg
End If
End With
End Sub

Private Function IsRtf(filename As String) As Boolean
Dim firstLine As String
IsRtf = False

Open filename For Input As #1
Line Input #1, firstLine
Close #1

If LCase(Left(firstLine, 6)) = "{\rtf1" Then
IsRtf = True
End If
End Function

--
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