因此我有一系列字符串想要在 Word 文档中搜索和替换。
我的字符串将显示为一个两列表格。我可能会使用 Word 创建表格,然后手动将其转换为 TXT、CSV 或任何可行的格式……我不需要自动执行该部分。表格大致如下所示:
English word French word
dog chien
cat chat
London Londres
你明白了...
我需要一个宏来搜索第一列中包含的术语,并用第二列的内容替换它们。
你能帮忙吗?谢谢!
答案1
Selection.Find.ClearFormatting
With Selection.Find
.Text = "English Word"
.Replacement.Text = "French Word"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
为每个单词创建一个,但这不会读取你的表格
答案2
我冒昧地借用了 Raystafarian 的代码片段并对其进行了扩展。您将使用filename="c:\folder\file.txt
纯文本文件的路径和文件名更改该行,其中的内容是一个单词或短语,后跟一个制表符,后跟一个单词或短语,后跟行尾。我没有费心进行错误检查,因此如果最后一行没有行尾,则不会替换该行的文本。此外,如果您没有在每行中包含制表符,则此宏可能会中断。备份您的 word 文档以方便轻松恢复。
Sub Macro1()
Dim ff As Long
Dim x As Long
Dim filename As String
Dim buffer As String
Dim charbuffer As String * 1
filename = "c:\folder\file.txt"
ff = FreeFile
Open filename For Binary As ff
buffer = ""
charbuffer = ""
For x = 1 To LOF(ff)
Get #ff, , charbuffer
If charbuffer <> vbCr And charbuffer <> vbLf Then
buffer = buffer & charbuffer
Else
If buffer <> "" Then processBuffer buffer
buffer = ""
End If
Next x
Close ff
End Sub
Sub processBuffer(buffer As String)
Dim varArray As Variant
varArray = Split(buffer, vbTab)
makeReplacements varArray(0), varArray(1)
End Sub
Sub makeReplacements(ByVal strToReplace As String, ByVal strReplacement As String)
'MsgBox strToReplace & " will be replaced by " & strReplacement
Selection.Find.ClearFormatting
With Selection.Find
.Text = strToReplace
.Replacement.Text = strReplacement
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
End Sub