下面的VBA Word宏是在选择几个段落或本例中选择所有段落后运行的。我附加了一个运行宏的示例.rtf文件
除了有超链接的段落外,段落开头的圣经参考文献都有一对。我的宏有错吗?或者这是Word 2010的问题吗?
其次,了解这是否适用于Office 365会很有帮助(我在LibreOffice上也尝试过同样的方法,即使单词是超链接的,它也会匹配
(^(([A-Z123I]{1,3}[^]{1,15}(([0-9]{1.3}:[0-9-\–]{1,7}(
$1$2$3$2$3
所以请不要说我没有努力寻找这是否可行,或者我没有尝试过不同的设置。如果有人发帖说这对他们来说不起作用,至少表明他们已经花时间下载了宏测试文件并实际进行了测试,这会更有帮助(
Private Sub RelRefWithBibleName_Click()
InSelection = False
If selection.Type = wdSelectionIP Then InSelection = True
If InSelection = True Then
MsgBox ("select some text")
Exit Sub
End If
selection.Find.ClearFormatting
selection.Find.Replacement.ClearFormatting
selection.Find.Replacement.Font.Reset
Application.ScreenUpdating = False
With selection
'Added this to make selection go beyond the start of the selected paragraph
'so that the detection would work
selection.MoveStartUntil Cset:=wdCharacter, Count:=wdBackward
strFindText = "([^13])([A-Z123I ]{1,3}[! ]{1,15} )([0-9]{1,3}:[0-9-–]{1,7})"
strReplaceText = "1<ref>23</ref>23"
End With
With selection.Find
.MatchWildcards = True
.ClearFormatting
.Replacement.ClearFormatting
.text = strFindText
.Replacement.text = strReplaceText
.Format = False
.MatchWholeWord = True
.Forward = True
.Wrap = wdFindStop
End With
selection.Find.Execute Replace:=wdReplaceAll
selection.Shrink
selection.Move
Application.ScreenUpdating = True
selection.Find.ClearFormatting
selection.Find.Replacement.ClearFormatting
End Sub
循环浏览超链接集合没什么大不了的。也就是说,还有另一种方法:
Sub Demo()
Application.ScreenUpdating = False
Dim RngFnd As Range, StrTxt As String
With Selection
Set RngFnd = .Range
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "[A-Z1-3 ]{1,3}[! <>]{1,15} [0-9]{1,3}:[0-9-?]{1,7}"
.Replacement.Text = ""
.Forward = True
.Format = False
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
If .InRange(RngFnd) Then
If .Paragraphs.Count > 1 Then .Start = .Paragraphs(1).Range.End
If .Start = .Paragraphs(1).Range.Start Then
StrTxt = .Text
.InsertBefore "<ref>" & StrTxt & "</ref>"
.Font.Bold = False
.Start = .End - Len(StrTxt)
.Font.Bold = True
End If
If .Hyperlinks.Count > 0 Then
If .Hyperlinks(1).Range.Start = .Paragraphs(1).Range.Start Then
With .Hyperlinks(1).Range
StrTxt = .Text
.InsertBefore "<ref>" & StrTxt & "</ref>"
.Font.Bold = False
.Start = .End - Len(StrTxt)
.Font.Bold = True
End With
End If
End If
Else
Exit Do
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End With
RngFnd.Select
Application.ScreenUpdating = True
End Sub
您的查找/替换表达式没有错,尽管它们可以简化:
strFindText = "([^13])([A-Z1-3 ]{1,3}[! ]{1,15} [0-9]{1,3}:[0-9-–]{1,7})"
strReplaceText = "1<ref>2</ref>2"
Word版本无关紧要。对于超链接,您可以循环浏览超链接集合,如果适用,在将标记插入其两侧之前,测试显示文本。