我需要在word文档中找到一个字符串并使用vba代码替换它的子字符串。
答案 0 :(得分:0)
您可以这样做:
Sub Macro1()
Dim TextToFind as String
TextToFind = "test"
Dim TextToReplace as String
TextToReplace = "testing"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = TextToFind
.Replacement.Text = TextToReplace
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
这是直接从Word中的记录宏功能中提取的。
答案 1 :(得分:0)
将Mid方法用于子字符串目的
Sub WordReplace()
Dim sSample, rResult As String
sSample = "hello world is my program"
' Sub String (replacing word)
rResult = Mid(sSample, 1, 5)
Set rRange = ActiveDocument.Content
rRange.Find.Execute FindText:=sSample, ReplaceWith:=rResult, Replace:=wdReplaceAll
End Sub