如何强制下划线成为Word宏中单词的一部分?

时间:2014-01-15 19:29:29

标签: vba ms-word

我正在尝试为一个非常大的Word文档编写一个查找和替换宏。我有一个Excel文件,其中包含我要替换的4100多行was / now数据。我可以成功遍历该文件以提取我正在寻找的单词,以及我想要替换它的单词。但是,我的条目都包含下划线。我遇到的问题是Word将下划线视为一个新单词。所以,例如,我想用“雪”代替“苹果”。我想要替换以下示例:“apple”,“apple”,“apple。”,“apple(”。我不希望在以下示例中替换“apple”:“pineapple”,“apple_x “。我试图使用通配符,但是在我的例子”apple_x“中会发生什么,它会将其更改为”snow_x“。有没有人知道如何强制下划线成为单词的一部分?谢谢。

以下是我目前正在尝试使用的代码:

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

2 个答案:

答案 0 :(得分:0)

Sub ReplaceJamieLannister()

    Set rng2 = ActiveSheet.UsedRange
    For Each Cell In rng2
    If Left(Cell.Value, 1) = "J" And Mid(Cell.Value, 6, 1) <> "_" Then


    Cell.Replace "Jamie", "King Slayer", xlPart

    End If

    Next Cell

End Sub

之前的数据:

Jamie
Jamie,
Jamie)
Jamie.
Jamie_Lannister
PineJamie

数据之后:

King Slayer
King Slayer,
King Slayer)
King Slayer.
Jamie_Lannister
PineJamie

答案 1 :(得分:0)

以下是我如何做到这一点,不确定这是最好的方法,但似乎工作得很好!

以下是我的代码生成

enter image description here

以下是代码

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