所以我有一个.txt文件,它是一个特殊单词列表,我希望我的宏读取文本文件并在打开的文档中突出显示文本文件中第一次出现的字符串第1行,重复直到结束文件。此代码有效,但它只找到第一个出现的第一个字符串,并且找不到任何后续字符串。没有错误。我知道正在读取行(取消注释msgbox mystring并显示文本文件中的每个字符串)。我做错了什么?
Sub acronym_highlighter()
Dim MyString As String
Dim MyAcroFileName As String
'Ask user for name of file
MyAcroFileName = InputBox("Enter the filename containg the acronyms. This file MUST be .txt format:", vbOKOnly, "Enter file name")
Open MyAcroFileName For Input As #1
'loop through the file until the end of file marker
'is reached
Do While Not EOF(1)
'read line of text, place it in the MyString variable
Line Input #1, MyString
' MsgBox MyString
Options.DefaultHighlightColorIndex = wdYellow
Selection.Find.Replacement.Highlight = True
With Selection.Find
.Text = MyString
.Replacement.Text = MyString
End With
Selection.Find.Execute Replace:=wdReplaceOne
Loop
'close the text file
Close #1
End Sub
答案 0 :(得分:0)
似乎Selection.Find.Execute
正在改变文档中的实际Selection
(Range
),从而产生意外结果。在第一次迭代之后,Selection
成为刚刚替换的单词 - 不多也不少 - 显然其他单词未在<<>中找到 / em>那个词Range
。
确保您正在查看整个文档,例如:
Do While Not EOF(1)
'read line of text, place it in the MyString variable
Line Input #1, MyString
'Reset the Range object to the entire current document
Set rng = ActiveDocument.Range
rng.Find.Replacement.Highlight = True
With rng.Find
.Text = myString
.Replacement.Text = myString
.Execute Replace:=wdReplaceOne
End With
Loop