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

时间:2013-09-20 14:05:39

标签: vba ms-word

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

这就是我现在所拥有的。

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

不起作用的宏:

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

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

1 个答案:

答案 0 :(得分:3)

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

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

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

取代所有出现的Text with Tax ....这就是你要追求的?

也适用于变量

OldWord = "VAT"
NewWord = "Text"

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

添加,Matchcase:=结束时为True以修复案例问题(现在在上面修改)

第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