CodeItBetter Programming Another VB Programming Blog

How to add text to Microsoft Word documents from VB

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
'MS Office - How to add text to Microsoft Word documents from VB
'This code uses Microsoft Word to add text to documents, from VB.
'First, don't forget to set a reference to the Word 8.0/9.0/10.0/11.0/12.0 Object Model.

Public Function AddTextToWordDoc(ByVal strFileName As String, ByVal strText As String)
    Dim oWordApp As Word.Application
    Dim oWordDoc As Word.Document
    Dim oWordSel As Word.Selection
 
    On Error Resume Next
    Set oWordApp = GetObject(, "Word.Application")  'Look For a running copy of Word.
    If Err.Number <> 0 Then    'If Word is Not running then, run it.
        Set oWordApp = CreateObject("Word.Application")
    End If
 
    oWordApp.Documents.Open strFileName, False, False, False
    'To show Microsoft word application
    'oWordApp.Visible = True
    Set oWordDoc = oWordApp.Documents(Right$(strFileName, Len(strFileName) - _
        InStrRev(strFileName, "\")))
    'To goto top of the document
    oWordDoc.Bookmarks("\StartOfDoc").Range.Select
 
    Set oWordSel = Word.Selection
 
    oWordDoc.Range.InsertBefore strText
 
    'To save the document
    oWordDoc.Save
 
    'To quit the word application
    oWordApp.Quit True
 
    Set oWordApp = Nothing
    Set oWordDoc = Nothing
    Set oWordSel = Nothing
End Function
Filed under: MS Office Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.