Add Formatted Text to Word from VBScript


Windows is full of COM (Component Object Model), and many software (such as Microsoft Office) provides the COM automation object, that can be easily programmed.

The following shows an example of using Word from VBScript at WSH (Window Script Hosting) environment. The Word.Application is the automation object to create.

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
' create word object
Set objWord = CreateObject("Word.Application")
 
objWord.Visible = True
 
' add a document
Set objDoc = objWord.Documents.Add()
 
' obtain selection handler
Set objSelection = objWord.Selection
 
' set the font and add a text paragraph
objSelection.Font.Name = "Arial"
objSelection.Font.Size = "18"
objSelection.TypeText "Network Adapter Report"
objSelection.TypeParagraph()
 
' set the font and add a text paragraph
objSelection.Font.Size = "14"
objSelection.TypeText "" & Date()
objSelection.TypeParagraph()
 
' bring to front
objWord.Application.Activate
objWord.Application.WindowState = wdWindowStateMaximize
CreateObject("WScript.Shell").AppActivate objDoc.Name
' create word object
Set objWord = CreateObject("Word.Application")

objWord.Visible = True

' add a document
Set objDoc = objWord.Documents.Add()

' obtain selection handler
Set objSelection = objWord.Selection

' set the font and add a text paragraph
objSelection.Font.Name = "Arial"
objSelection.Font.Size = "18"
objSelection.TypeText "Network Adapter Report"
objSelection.TypeParagraph()

' set the font and add a text paragraph
objSelection.Font.Size = "14"
objSelection.TypeText "" & Date()
objSelection.TypeParagraph()

' bring to front
objWord.Application.Activate
objWord.Application.WindowState = wdWindowStateMaximize
CreateObject("WScript.Shell").AppActivate objDoc.Name

You see, very straightforward and easy to do the automation tasks. The above script produces the following.

word Add Formatted Text to Word from VBScript batch script beginner code implementation programming languages tricks VBA vbscript windows windows command shell windows scripting host

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
228 words
Last Post: Fast Integer Log10
Next Post: Copy Function in Delphi XE3

The Permanent URL is: Add Formatted Text to Word from VBScript

Leave a Reply