如何在我的Word宏中强制下划线成为单词的一部分? [英] How can I force an underscore to be part of a word in my Word macro?
问题描述
我正在尝试为一个非常大的Word文档编写一个查找并替换宏.我有一个包含要替换的was/now数据的4100+行的Excel文件.我可以成功地遍历该文件,以拔出我要查找的单词,以及想要替换为该单词的单词.但是,我的所有输入都包含下划线.我遇到的问题是Word将下划线视为新单词.因此,例如,我想将"apple"替换为"snow".我希望替换以下示例:"apple","apple","apple.","apple(").我不希望在以下示例中替换"apple":"pineapple","apple_x .我尝试使用通配符,但是在我的示例"apple_x"中会发生什么,它将更改为"snow_x".有人知道如何强制下划线成为单词的一部分吗?谢谢.
I am trying to write a find and replace macro for a very large Word document. I have an Excel file that contains 4100+ rows of was/now data that I want to replace. I can successfully loop through that file to pull out the word I am looking for, and the word I want to replace it with. However, my entries all contain underscores. The problem that I am running into is that Word treats an underscore as a new word. So, for example, I want to replace "apple" with "snow". I would like the following examples to be replaced: "apple", "apple,", "apple.", "apple(". I would NOT like "apple" to be replaced in the following examples: "pineapple", "apple_x". I attempted to use wildcards, but what happens is in my example "apple_x", it will change it to "snow_x". Does anyone know how to force the underscore to be part of the word? Thank you.
这是我当前尝试使用的代码:
Here is the code I am currently trying to use:
Sub MeasFindAndReplace()
Dim objExcel, path, filename, i, objFind, objReplace
path = "C:\"
filename = "Test.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Open path & filename
objExcel.Workbooks(filename).Activate
For i = 2 To 4150
If StrComp(objExcel.Worksheets("Master").Cells(i, 2), "", 1) = 0 Then
Exit For
Else
objFind = objExcel.Worksheets("Master").Cells(i, 2).Value
objReplace = objExcel.Worksheets("Master").Cells(i, 3).Value
RepeatMeasFindAndReplace objFind, objReplace
End If
Next i
objExcel.Quit
End Sub
Sub RepeatMeasFindAndReplace(objFind, objReplace)
objFind = "<" + objFind + ">"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
If Not Selection.Information(wdWithInTable) Then
With Selection.Find
.Text = objFind
.Replacement.Text = objReplace
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End If
End Sub
推荐答案
这是我要这样做的方式,不确定这是否是最好的方法,但这似乎还可以!
Here's how I'd do this, not sure it's the best way to do it, but it seems to work JUST fine!
这是我的代码产生的结果:
这是代码:
Sub SuperReplace()
last = Cells(Rows.Count, 1).End(xlUp).Row
For x = 1 To last
replacein = Cells(x, 1)
replacewhat = Cells(x, 2)
replacewith = Cells(x, 3)
If replacein Like "*" & replacewhat & "*" And _
InStr(replacein, "_") = 0 Then
replacein = Replace(replacein, replacewhat, replacewith)
Cells(x, 5) = replacein
End If
Next
End Sub
这篇关于如何在我的Word宏中强制下划线成为单词的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!