简体   繁体   English

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

[英]MS WORD VBA Find Replace text using a variable

I have a variable (strLastname) that I use to send a string to a bookmark. 我有一个变量(strLastname),用于将字符串发送到书签。 That works well. 那很好。 I also wish to use that variable to replace temporary text "Name>" in a long document. 我还希望使用该变量替换长文档中的临时文本“名称>”。

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.Value but no one work. Replacement.Text = strLastname and .Replacement.Text = BoxLastname.Value但是没有一个起作用。

A quick search from google finds this link http://msdn.microsoft.com/en-us/library/office/aa211953(v=office.11).aspx 从Google进行的快速搜索找到此链接http://msdn.microsoft.com/zh-cn/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 ?? 那用Tax代替了所有出现的Text ....这是您所追求的吗?

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) Add,Matchcase:= True可以解决大小写问题(上面已修改)

3rd Modification results in this 第三修改导致

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM