我正在编写一个用于在Word文档中定义首字母缩略词的模块。该脚本从Excel文档中获取首字母缩写词和定义。我遇到的问题是将首字母缩略词的第一个实例的位置与完整定义的第一个实例的位置进行比较。 最后,我需要确保首字母缩写的第一个实例在定义的第一个实例之后立即出现,括在括号中。完成此操作后,脚本将需要删除定义的后续实例,因此我还需要弄清楚除了定义的第一个实例之外的所有实例。
最终结果应如下所示:
....本文档是关于软件即服务(SaaS)的。 SaaS是由其他人托管的软件。您可以通过Web浏览器访问它,而不是将其安装在您自己的计算机上。 SaaS有很多种类型。 ....
我如何获得这两个元素的位置和/或比较它们的位置?
在上面的例子中,我如何找到" SaaS"的第一个实例。并确保它在(空格,开括号)定义之后恰好出现两个位置(假设定义实际出现在文档中)?
'Selects first instance of acronym. Get start and end positions of first instance of acronym.
Selection.HomeKey Unit:=wdStory
Selection.Find.Execute Acronym 'Acronym is a variable. Now that it's selected, I need to get it's start position (or the position of the cursor if the cursor is at the start of the acronym) or find a way to compare it's position to the UserSelection variable.
'Is the definition in the document?
'If no, add definition before first instance of acronym.
'If yes, get start and end positions of first instance of definition.
'Is end position of first instance of definition adjacent to start position of first instance of acronym? If not, which is first?
'If definition is first, add acronym behind definition.
'If acronym is first, add definition in front of acronym and delete remaining instances of definition.
'Highlights all instances of the acronym in green
With ActiveDocument.Content.Find
.MatchCase = True
.MatchWholeWord = False
With .Replacement
.Highlight = True
End With
.Execute Replace:=wdReplaceAll, Wrap:=wdFindContinue, FindText:=Acronym, ReplaceWith:=Acronym
End With
任何帮助或见解都会受到赞赏,因为我完全不知所措,并且对谷歌没有运气。
-Vince
答案 0 :(得分:0)
我认为以下代码段可以为您提供帮助:
Sub example(acronym, definition)
Selection.Find.ClearFormatting
With Selection.Find
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchAllWordForms = False
End With
ActiveDocument.Range(0, 0).Select ' go to beginning of document
Selection.Find.Text = acronym
Selection.MatchSoundsLike = False
If (Not Selection.Find.Execute) Then
' acronym not found in this document
Exit Sub
End If
ActiveDocument.Range(0, 0).Select ' go to beginning of document
Selection.Find.Text = definition
Selection.MatchCase = False
Selection.MatchSoundsLike = True
While (Selection.Find.Execute)
'
Selection.Delete ' delete all definitions
'
Wend
ActiveDocument.Range(0, 0).Select ' go to beginning of document
Selection.Find.Text = acronym
Selection.MatchSoundsLike = False
If (Selection.Find.Execute) Then
Selection.InsertBefore "(" & definition & ")"
End If
End Sub
注意:我还发现作者在定义中犯了错误(微小的变化),甚至一个额外的非预期空间也会使发现变得混乱。