gpt4 book ai didi

excel - VBA搜索从excel中替换word文档中的文本

转载 作者:行者123 更新时间:2023-12-04 21:51:27 26 4
gpt4 key购买 nike

我正在尝试制作一个 excel 文档,我可以粘贴一个单词列表来搜索和替换。我想使用 excel 文档在 word 文档中搜索和替换这些单词。

我在使代码正常运行时遇到问题。

Sub SearchReplace()

Dim WordDoc As Object, N As Variant, i As Integer, j As Integer
i = Range("C2").Value 'pulls length of list from an excel function located in cell C2
N = Range("B4:C" & CStr(i + 3)).Value
Set WordDoc = CreateObject(Class:="Word.Application")
WordDoc.Visible = True
WordDoc.Documents.Open Filename:="C:\WordTest.docm"
WordDoc.Activate
With WordDoc.ActiveDocument
For j = 1 To i
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = False
.Wrap = wdFindContinue
.Text = N(1, j)
.Replacement.Text = N(2, j)
.Execute
End With
End With
Next j
End With
WordDoc.Quit
Set WordDoc = Nothing
End Sub

我根据建议更正了代码,并且不再出现任何错误。但是,该代码似乎没有在指定的 Word 文档中查找和替换任何内容。我试图通过输入特定单词“text”和特定单词“replace”来简化代码以检查查找和替换部分,以在包含单词“text”的word文档中查找和替换。这仍然没有改变。我删除了关闭文档的行,以防问题是文档在更新后没有保存,但这也不成功,所以我将 WordDoc.Quit 添加回代码中。
Sub SearchReplace()

Dim WordDoc As Object, N As Variant, i As Integer, j As Integer

i = Range("C2").Value 'pulls length of list from an excel function
located in cell C2
N = Range("B4:C" & CStr(i + 3)).Value
Set WordDoc = CreateObject(Class:="Word.Application")
WordDoc.Visible = True
WordDoc.Documents.Open Filename:="C:\WordTest.docm"
WordDoc.Documents("WordTest.docm").Activate
With WordDoc.ActiveDocument
For j = 1 To i
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = False
.Wrap = 1
.Text = "text" 'N(j, 1)
.Replacement.Text = "replace" 'N(j, 2)
.Execute 2
End With
End With
Next j
End With
WordDoc.Quit
Set WordDoc = Nothing
End Sub

最佳答案

我能够让代码正常工作。代码使用存储在代码中的数组中的 Excel 工作表(B4:B5004(查找)、C4:C5005(替换))中的查找替换字符串列表从 Excel 中搜索指定的 Microsoft Word 文档。

为了让代码发挥作用,我必须包含 Microsoft Word 16 对象库。

从 excel VBA 编辑器窗口。
工具 > 引用,然后确保选中 Microsoft Word 16.0 对象库。

Option Explicit

Sub SearchReplace()

Dim WordApp As Object, WordDoc As Object, N As Variant, i As Integer, j As Integer
i = Range("C2").Value 'pulls length of list from an excel function located in cell C2 =COUNTIF(B4:B5005,"*")
N = Range("B4:C" & CStr(i + 3)).Value
Set WordApp = CreateObject(Class:="Word.Application")
Set WordDoc = WordApp.Documents.Open("C:\WordTest.docm")
WordDoc.Visible = True
For j = 1 To i
With WordApp
With WordDoc.Content.Find
.Text = N(j, 1)
.Replacement.Text = N(j, 2)
.Wrap = wdFindContinue
.MatchWholeWord = True
.Execute Replace:=wdReplaceAll
End With
End With
Next j
WordApp.ActiveDocument.Save
WordApp.ActiveDocument.Close
WordApp.Quit

Set WordApp = Nothing
Set WordDoc = Nothing
End Sub

关于excel - VBA搜索从excel中替换word文档中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com