Open a Word Document

  • Thread starter Thread starter Frank
  • Start date Start date
F

Frank

Hi I have a userform that collects all word doc from
directory into a list box, now I need to open a doc when
the user select one and write the user name to the Author
part can this be done in excel vba if so can someone help
please.
Frank.
 
Hi I have a userform that collects all word doc from
directory into a list box, now I need to open a doc when
the user select one and write the user name to the Author
part can this be done in excel vba if so can someone help
please.

You can call the following function to do that. (The function has been
tested, but is NOT bullet-proof. Error handling is rudimentary):

------------------------------------

Function OpenSelectedWordDocument _
(FullNameOfDoc As String, _
Optional AuthorName As String) As Boolean

Dim wdApp As Object
Dim wdDoc As Object

On Error GoTo ErrorHandler

OpenSelectedWordDocument = False

'Open a new instance of Word and make it
'visible.
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True

'Open the selected document, the name of which
'you have passed as an argument to this function.
'NB: I assume that your existing process confirms that
'this file exists.
Set wdDoc = wdApp.Documents.Open(Filename:=FullNameOfDoc)

'If no user name is passed to the function, use the one
'defined in Office.
If AuthorName = "" Then
wdDoc.BuiltinDocumentProperties("Author") _
= Application.UserName
Else
wdDoc.BuiltinDocumentProperties("Author") _
= AuthorName
End If

'Return value of the function; signifies successful completion.
OpenSelectedWordDocument = True

ExitPoint:

Set wdDoc = Nothing
Set wdApp = Nothing

Exit Function

ErrorHandler:
MsgBox "Sorry, unable to open the Word file. The following error
occurred:" _
& vbCrLf & Err.Number & vbCrLf & Err.Description

Resume ExitPoint

End Function

---------------------

The following example procedure shows how to run it. You'd probably do
that from a command button on your user form:

Sub TestOpen()

'You would pass the file name that your user has selected
'rather than a hard coded string, obviously.

OpenSelectedWordDocument _
"H:\Word_And_Documents\Tests_Development\TestDoc1.doc", "Hank S."

End Sub
 
Back
Top