excel 中的宏,用于替换 word 文档中的确切文本
macro in excel for replacing exact text in word document
我正在尝试替换 word 文档中的 100 个测试 ID。我从该站点找到并使用了下面提到的宏。我面临的问题是,这个逻辑并没有替换完全匹配的值。当我尝试将测试 ID AUTO_1 更改为 AUTO_A 时,它还会将测试 ID AUTO_10 更改为 AUTO_A0 并将 AUTO_11 更改为 AUTO_A1.
Sub test1()
Dim pathh As String
Dim pathhi As String
Dim oCell As Integer
Dim from_text As String, to_text As String
Dim WA As Object
pathh = "C:.doc"
Set WA = CreateObject("Word.Application")
WA.Documents.Open (pathh)
WA.Visible = True
For oCell = 1 To 100
from_text = Sheet1.Range("A" + CStr(oCell)).Value
to_text = Sheet1.Range("B" + CStr(oCell)).Value
With WA
.Activate
With .Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = from_text
.Replacement.Text = to_text
.Execute Replace:=wdReplaceAll
End With
End With
Next
End Sub
尝试将 from_text 更改为:
from_text = Sheet1.Range("A" + CStr(oCell)).Value & " "
您也可以反向循环,以便首先替换较大的数字:
For ocell = 100 to 1 Step -1
...
Next ocell
我正在尝试替换 word 文档中的 100 个测试 ID。我从该站点找到并使用了下面提到的宏。我面临的问题是,这个逻辑并没有替换完全匹配的值。当我尝试将测试 ID AUTO_1 更改为 AUTO_A 时,它还会将测试 ID AUTO_10 更改为 AUTO_A0 并将 AUTO_11 更改为 AUTO_A1.
Sub test1()
Dim pathh As String
Dim pathhi As String
Dim oCell As Integer
Dim from_text As String, to_text As String
Dim WA As Object
pathh = "C:.doc"
Set WA = CreateObject("Word.Application")
WA.Documents.Open (pathh)
WA.Visible = True
For oCell = 1 To 100
from_text = Sheet1.Range("A" + CStr(oCell)).Value
to_text = Sheet1.Range("B" + CStr(oCell)).Value
With WA
.Activate
With .Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = from_text
.Replacement.Text = to_text
.Execute Replace:=wdReplaceAll
End With
End With
Next
End Sub
尝试将 from_text 更改为:
from_text = Sheet1.Range("A" + CStr(oCell)).Value & " "
您也可以反向循环,以便首先替换较大的数字:
For ocell = 100 to 1 Step -1
...
Next ocell