簡體   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