VBA宏:Excel到Word文本替换
Excel(2003)有简单的VBA宏。它查找单元格A$N和B$N,并将Word文档中的文本从B$N替换为A$NVBA宏:Excel到Word文本替换,excel,vba,ms-word,Excel,Vba,Ms Word,Excel(2003)有简单的VBA宏。它查找单元格A$N和B$N,并将Word文档中的文本从B$N替换为A$N Sub Макрос1() Dim pathh As String, i As Integer pathh = "c:\1.doc" Dim pathhi As String Dim from_text As String, to_text As String Dim WA As Object, WD As Object Set WA = CreateObject("Word.Ap
Sub Макрос1()
Dim pathh As String, i As Integer
pathh = "c:\1.doc"
Dim pathhi As String
Dim from_text As String, to_text As String
Dim WA As Object, WD As Object
Set WA = CreateObject("Word.Application")
WA.Documents.Open (pathh)
WA.Visible = True
For oCell = 1 To 150
from_text = Range("B" + CStr(oCell)).Value
to_text = Range("A" + 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
问题:在Word文档中,此脚本仅选择文本,但不进行替换。有什么建议吗?首先,我希望您激活对Word对象库的引用: 脚本实际工作时,我做了一些小的修改,包括替换:
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:\1.doc"
Set WA = CreateObject("Word.Application")
WA.Documents.Open (pathh)
WA.Visible = True
For oCell = 1 To 2
from_text = Sheet2.Range("B" & oCell).Value
to_text = Sheet2.Range("A" & 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
使用Excel VBA 7.0和Word 14.0时,需要稍微修改选择块中的对象
With .Selection.find
.ClearFormatting
.Execute FindText:=from_text, ReplaceWith:to_text, replace:=wdReplaceAll
End With
你有我的尺寸和使用oCell代替优秀的建议!Ms Excel和Ms Office库已链接到该项目,但Ms Word-否。