繁体   English   中英

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

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

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

这就是我现在所拥有的。

  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但是没有一个起作用。

从Google进行的快速搜索找到此链接http://msdn.microsoft.com/zh-cn/library/office/aa211953(v=office.11​​).aspx

我在一个简单的文档上尝试过查找并替换文本

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

那用Tax代替了所有出现的Text ....这是您所追求的吗?

也适用于变量

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

第三修改导致

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