vbscript在word文档中查找/替换字符串

时间:2012-11-14 12:12:55

标签: vbscript

我正在尝试创建一个VB脚本,它将执行word文档中某些字符的替换,并按以下方式进行管理:

objSelection.Find.Text = "["
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "q"
objSelection.Find.Execute ,,,,,,,,,,2
objSelection.Find.Text = "{"
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "w"
objSelection.Find.Execute ,,,,,,,,,,2
objSelection.Find.Text = "^"
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "y"
objSelection.Find.Execute ,,,,,,,,,,2
objSelection.Find.Text = "~"
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "z"
objSelection.Find.Execute ,,,,,,,,,,2
objSelection.Find.Text = "]"
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "x"
objSelection.Find.Execute ,,,,,,,,,,2
objSelection.Find.Text = "}"
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "ć"
objSelection.Find.Execute ,,,,,,,,,,2
objSelection.Find.Text = "@"
objSelection.Find.Forward = TRUE
objSelection.Find.Replacement.Text = "]"
objSelection.Find.Execute ,,,,,,,,,,2

但是,我设法做的方式非常慢,尤其是当文本文件为几MB时增加需要替换的字符数...所以,脚本会遍历整个文档每个替换字符,结果是脚本执行速度非常慢。是否有可能在word文档中并行更改多个字符,脚本只有一个通过文档并根据遇到的字符执行替换? 我还尝试逐行从word文档加载到变量中,并将每个字符与给定字符进行比较以进行替换,这导致脚本执行速度慢得多...... 对不起我的英语,我希望我成功地解释了我的问题。 请帮我。谢谢。 :)

1 个答案:

答案 0 :(得分:0)

你可以这样做吗?

objSelection.Find.ClearFormatting
With objSelection.Find
    .Text = "[\[\{~\]\}\@^0094]" ' ^0094 is "^"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = 1 'wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
End With

Do While objSelection.Find.Execute()
    Dim t: t = objSelection.Text
    Select Case t
        Case "["
            objSelection.Text = "q"
        Case "{"
            objSelection.Text = "w"
        Case "~"
            objSelection.Text = "z"
        '... fill in the rest
    End Select
    objSelection.Move 1
Loop

我认为这可能只有在您查找并替换单个字符时才有效,但这样做与您要查找的任何字符相匹配,检查找到的字符并用适当的字符替换它。

这是从Word 2010中记录的宏中获取的,但我认为不应该转换为VBScript。