我正在创建一个宏来搜索 Word 文档,以查找与 Excel 文件中的首字母缩写词完全匹配的内容。如果首字母缩略词在 Word 文件中,则宏突出显示首字母缩略词并将行号插入到数组中,以便在要编写的宏中使用以生成首字母缩略词表。
下面的宏有效,但是每当我运行它时都会出现几个误报。当某些首字母缩略词包含特殊字符时会发生这种情况,特别是“&”、“/”和“-”。
例如,如果我在包含 RT&E 的文件上运行以下宏,代码会将 "RT 和 "RT&E" 和 "T&E" 的行号插入到数组中(前提是所有三个都在 excel 文件的第一列中)。
这对小文档来说不是问题,但对于 150 页的文档来说,这实在是太多了。我也为糟糕的代码道歉。感谢您提出使其更好的建议。
Dim rng As range
Dim i As Long
Dim acro As String
Dim acrolist As Excel.Application
Dim acrobook As Excel.Workbook
Dim acromatch() As Variant
ReDim acromatch(0 To 1)
Set acrolist = New Excel.Application
Set acrobook = acrolist.Workbooks.Open("P:\AcronymMacro\MasterAcronymList.xlsm")
' Count from first row with acronym to maximum # of rows
' That way, list can be as long or short as needed
For i = 3 To 1048576
Set rng = ActiveDocument.range
acro = acrobook.Sheets(1).Cells(i + 1, 1)
' Loop breaks when it finds an empty cell
' i.e. the last acronym in the document.
If acro = "" Then Exit For
' Find and Replace code
With rng.Find
.Text = acro
.Format = True
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
' Do While loop
Do While .Execute(Forward:=True) = True
rng.HighlightColorIndex = wdPink
Call InsertIntoArray(acromatch(), i + 1)
Loop
End With
Next
MsgBox Join(acromatch(), ",")
'Make sure you close your files, ladies and gentlemen!
acrobook.Close False
Set acrolist = Nothing
Set acrobook = Nothing
' This function resizes array and insert value as last value
Public Function InsertIntoArray(InputArray As Variant, Value As Variant)
ReDim Preserve InputArray(LBound(InputArray) To UBound(InputArray) + 1)
InputArray(UBound(InputArray)) = Value
End Function
我尝试的一件事是在 Do While 循环中运行另一个 Range.Find 方法,对首字母缩写词稍作更改。例如,下面的代码确保首字母缩写词后有空格、句点或右括号,而不是 & 和连字符。如果不同,则不会添加。
Do While .Execute(Forward:=True) = True
rng.HighlightColorIndex = wdPink
acro = acro + "[ .)]"
With rng.Find
.Text = acro
.MatchWildCards = True
If rng.Find.Execute(Forward=True) = True Then Call InsertIntoArray(acromatch(), i + 1)
End With
Loop
然而,这段代码确保没有任何东西进入数组。
当首字母缩略词中有特殊字符时,如何呈现误报?