Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection
objSelection.TypeText "Hardware Inventory"
objSelection.TypeParagraph()
objSelection.InsertFile("C:\Scripts\Hardware.txt")
objSelection.TypeParagraph()
objSelection.TypeText "Software Inventory"
objSelection.TypeParagraph()
objSelection.InsertFile("C:\Scripts\Software.txt")
正如我們剛剛說的,比起將好幾個檔案組成一個文字檔,這個作業要簡單多了。一開始我們先建立 Word.Application 物件的執行個體,將 Visible 屬性設為 True;然後再加入一個文件,建立 Selection 物件的執行個體。這就是下面這幾行程式碼所做的事:
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection
這個動作原來就不難,現在則是更加容易。我們希望為硬體庫存加上標題,因此輸入「硬體庫存」作為標題,再加上段落換行字元;這就是下面程式碼所做的事:
objSelection.TypeText "Hardware Inventory"
objSelection.TypeParagraph()
接下來準備插入檔案,只需要一行程式碼就夠了:
objSelection.InsertFile("C:\Scripts\Hardware.txt")
就這樣:您先呼叫 InsertFile 方法,後面加上您要插入文件的檔案路徑。然後再加上另一個段落換行字元和「軟體庫存」標題,接著插入第二個檔案 C:\Scripts\Software.txt。很簡單吧,要我在這兒坐一整天,把檔案插入 Word 文件都可以!
不過,讓我們先在前面的指令碼,做一點小小的變化。這個動作會建立新的 Word 文件,然後插入所有在 C:\Scripts\Archive 資料夾下找到的檔案。在此就不逐行解說程式碼了,不過大部分您應該都看得懂:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection
Set FileList = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='C:\Scripts\Archive'} Where " _
& "ResultClass = CIM_DataFile")
For Each objFile In FileList
objSelection.InsertFile(objFile.Name)
objSelection.TypeParagraph()
Next
怎麼樣?酷吧?關於使用 Microsoft Office 應用程式的指令碼,如果您還想看看其他更酷更好玩的,不妨到 Script Center (Script 中心) 的 Office Space 專欄瞧瞧 (前面的廣告是由委員會贊助,目的在吸引更多人閱讀《Office Space》專欄)。 |