2017-06-06 58 views
0

因此,我有一个.txt文件,它是一个特殊字词列表,我希望我的宏读取文本文件并在打开的文档中突出显示第一次出现字符串行1从文本文件中重复,直到文件结束。此代码有效,但它只查找第一个字符串的第一个匹配项,并且找不到任何后续字符串的第一个匹配项。没有错误。我知道这些行正在被读取(取消注释msgbox mystring并显示文本文件中的每个字符串)。我究竟做错了什么?MS Word VBA,突出显示字符串第一次出现的代码

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

似乎Selection.Find.Execute被改变实际SelectionRange)在文件中,从而产生意外的结果。在第一次迭代后,Selection成为刚刚被替换的词 - 不多也不少 - 显然其他词没有找到之内,该词的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 
相关问题