我有一个表格,其中包含要在Word文档上替换的单词列表,并使用下面的代码。它工作得很好,直到最近我收到一条错误消息“字符串参数太长”,即超过 255 个字符。有人可以帮我解决这个问题吗?
我对编码/VBA的知识为零,我没有花时间学习它,因为我只需要进行文字处理。
Word 文档在桌面上的folder 中名称为doc。 Excel 工作表在桌面上的文件夹中命名为book。
非常感谢。
Option Explicit
Public Sub WordFindAndReplace()
Dim ws As Worksheet, msWord As Object, itm As Range
Set ws = ActiveSheet
Set msWord = CreateObject("Word.Application")
With msWord
.Visible = True
.Documents.Open "/Users/NAME/Desktop/folder/doc.docx"
.Activate
With .ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
For Each itm In ws.UsedRange.Columns("A").Cells
.Text = itm.Value2 'Find all strings in col A
.Replacement.Text = itm.Offset(, 1).Value2 'Replacements from col B
.MatchCase = False
.MatchWholeWord = False
.Execute Replace:=2 'wdReplaceAll (WdReplace Enumeration)
Next
End With
.Quit SaveChanges:=True
End With
End Sub
我使用 Excel 的数据 -> 文本到列 -> 固定宽度选项来分割冗长的列,然后用我质疑的相同代码替换它们。但最好的方法是修复代码并将替换内容复制到剪贴板。正如@macropod 所建议的
一种方法是将替换内容复制到剪贴板。例如:
Public Sub WordFindAndReplace()
Dim ws As Worksheet, msWord As Object, wdDoc As Object, itm As Range
Set ws = ActiveSheet
Set msWord = CreateObject("Word.Application")
With msWord
.Visible = True
Set wdDoc = .Documents.Open("/Users/NAME/Desktop/folder/doc.docx")
With wdDoc.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchCase = False
.MatchWholeWord = False
.Replacement.Text = "^c"
For Each itm In ws.UsedRange.Columns("A").Cells
itm.Offset(, 1).Copy 'Replacements from col B
.Text = itm.Value2 'Find all strings in col A
.Execute Replace:=2 'wdReplaceAll (WdReplace Enumeration)
Next
End With
.Quit SaveChanges:=True
End With
End Sub