用于查找和替换Word文档中的文本的VB脚本

时间:2011-05-25 18:11:28

标签: vbscript ms-word

我对VB Scripting没有太多经验,但我正在尝试编写一些能够在word文档中搜索特定字符串的内容,将其替换为我指定的内容,然后在标签打印机上打印出来。

第一次替换就好了,但不是第二次。任何人都可以看看我可能做错了什么?

Option Explicit

Dim WordApp
Dim WordDoc
Dim strReadCompName
Dim strReadCompSN

Set WordApp = CreateObject("Word.Application")
WordApp.Visible = TRUE

WordApp.Documents.Open("C:\LabelTemplate.doc")
WordApp.Documents("LabelTemplate.doc").Activate

Set WordDoc = WordApp.ActiveDocument

strReadCompName = InputBox("Enter Computer Name", "Name")
strReadCompSN = InputBox("Enter Serial Number", "Serial")

With WordApp.Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .MatchWholeWord = TRUE
    .Text = "nametext"
    .Execute ,,,,,,,,,strReadCompName
End With

With WordApp.Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .MatchWholeWord = TRUE
    .Text = "serialtext"
    .Execute ,,,,,,,,,strReadCompSN
End With

WordDoc.PrintOut()
WordDoc.Saved = TRUE
WordApp.Quit

1 个答案:

答案 0 :(得分:4)

解决了我自己的问题哈哈

Oracle认证专家是对的。我所要做的就是添加另一个语句将光标移回到开头。我刚刚将WordApp.Selection.GoTo 1添加到了开头。

Option Explicit
'Procedure to edit word document add name and serial number. 
Sub SearchAndRep(searchTerm, replaceTerm, WordApp)
    WordApp.Selection.GoTo 1
    With WordApp.Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .MatchWholeWord = True
        .Text = searchTerm
        .Execute ,,,,,,,,,replaceTerm
    End With
End Sub

Dim WordApp
Dim WordDoc
Dim strReadCompName
Dim strReadCompSN
Dim objNetwork, WSHPrinters, counter

'Enumerate through printers to find local Zebra printer.
Set objNetwork = CreateObject("WScript.Network")
Set WSHPrinters = objNetwork.EnumPrinterConnections

For counter = 0 To WSHPrinters.Count - 1 Step 2
    If Left(WSHPrinters.Item(counter +1), 5) = "Zebra" Then
        WScript.Echo(WSHPrinters.Item(counter +1))
        objNetwork.SetDefaultPrinter(WSHPrinters.Item(counter +1))
    End If
Next

'Create a Microsoft Word Object and make it invisible. 
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = FALSE

'Open LabelTemplate.doc for editing. 
Set WordDoc = WordApp.Documents.Open("C:\LabelTemplate.doc")

'Read in name and serial number to print on label. 
strReadCompName = InputBox("Enter Computer Name", "Name")
strReadCompSN = InputBox("Enter Serial Number", "Serial")

'Procedures to edit the Word Document to add name and serial number. 
SearchAndRep "nametext", strReadCompName, WordApp
SearchAndRep "serialtext", strReadCompSN, WordApp

'Print out the label. 
'WordApp.PrintOut()

'Set the default printer back to what it was before. 
'Still have to do this. 
objPrinter.SetDefaultPrinter "\\******\**********"
WordDoc.Saved = TRUE
WordDoc.Close
WordApp.Quit