MS WORD VBA 使用变量查找替换文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18918761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:26:15  来源:igfitidea点击:

MS WORD VBA Find Replace text using a variable

vbams-word

提问by Niala Celdak

I have a variable (strLastname) that I use to send a string to a bookmark. That works well. I also wish to use that variable to replace temporary text "Name>" in a long document.

我有一个变量 (strLastname),用于将字符串发送到书签。这很好用。我还希望使用该变量来替换长文档中的临时文本“名称>”。

This is what I have now.

这就是我现在所拥有的。

  Sub cmdOK_Click()
    Dim strLastname As String   ' from dialogue box "BoxLastname" field
    strLastname = BoxLastname.Value
....
  End sub

The macro that does not work:

不起作用的宏:

Sub ClientName()

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
    .Text = "Name>"
    .Replacement.Text = strLastname??????

             'Selection.TypeText (strLastname) ????
              'How to use the variable from the Dialogue Box - strLastname????

     End With
  Selection.Find.Execute Replace:=wdReplaceAll
End Sub

I tried .Replacement.Text = strLastname and .Replacement.Text = BoxLastname.Valuebut no one work.

我试过 。Replacement.Text = strLastname and .Replacement.Text = BoxLastname.Value但没有人工作。

回答by Tin Bum

A quick search from google finds this link http://msdn.microsoft.com/en-us/library/office/aa211953(v=office.11).aspx

从谷歌快速搜索找到这个链接 http://msdn.microsoft.com/en-us/library/office/aa211953(v=office.11​​).aspx

I tried this on a simple document to find and replace text

我在一个简单的文档上尝试了这个来查找和替换文本

With ActiveDocument.Content.Find
    .Forward = True
    .Wrap = wdFindStop
    .Execute FindText:="Text", ReplaceWith:="Tax", Replace:=wdReplaceAll

That replaces all occurence of Text with Tax .... is this what you're after ??

这用税收取代了所有出现的文本......这就是你所追求的吗??

Works with variables too

也适用于变量

OldWord = "VAT"
NewWord = "Text"

With ActiveDocument.Content.Find
    .Forward = True
    .Wrap = wdFindStop
    .Execute FindText:=OldWord, ReplaceWith:=NewWord, Replace:=wdReplaceAll, Matchcase:=True
End With

Add , Matchcase:=True at end to fix case problem (modified now above)

添加 , Matchcase:=True 在最后修复案例问题(现在修改上面)

3rd Modification results in this

第 3 次修改导致此

Dim strLastname As String   ' from dialogue box "BoxLastname" field
strLastname = BoxLastname.Value

OldWord = "Name"
NewWord = strLastName

With ActiveDocument.Content.Find
    .Forward = True
    .Wrap = wdFindStop
    .Execute FindText:=OldWord, ReplaceWith:=NewWord, Replace:=wdReplaceAll, Matchcase:=True
End With