VBA Open Word Doc
It's often necesarry to grab a word document to show information on a plugin or piece of code written in VBA, fortunately it's an incredbily easy thing to do! Here's the basic code that you can use to open a document:
Private Sub OpenDocs()
Dim Loc As String
Loc = "C:\test\test.doc"
Dim WordApp As Object
Dim WordDoc As Object
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(Filename:=Loc, ReadOnly:=True)
WordApp.Visible = True
'do your stuff
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
Of course a single, simple call as above is great but it's better to be able to call this as a class so that it can have further functionality added to it (it's often the case that you'll want to be able to programatically amend a document). A quick example of one way of doing this is below:
Note: as VBA doesn't support true inheritance some of the advantages that you'd get in a truly OO language are a little tougher to achieve
Option Explicit
Dim WordApp As Object
Dim WordDoc As Object
Dim Cleared As Boolean
Private Sub Class_Initialize()
Set WordApp = CreateObject("Word.Application")
Cleared = False
End Sub
Private Sub Class_Terminate()
If Not Cleared Then ReleaseDoc
End Sub
Public Sub ReleaseDoc()
Set WordDoc = Nothing
Set WordApp = Nothing
Cleared = True
End Sub
Public Sub OpenDoc(ByVal Path As String, _
Optional ByVal Visible As Boolean = True, _
Optional ByVal ReadOnly As Boolean = False)
Set WordDoc = WordApp.Documents.Open(Filename:=Path, ReadOnly:=ReadOnly)
MakeVisble Visible
End Sub
Public Sub MakeVisble(ByVal Visible As Boolean)
WordApp.Visible = Visible
End Sub
Obviously this is more of a shell than anything else but as time goes on I'll Add more functionality to this template
