【发布时间】:2018-10-27 13:08:29
【问题描述】:
更新:按照下面 Cindy 的建议,我使用了 InRange 函数。我的函数通过 Find 操作进行了很好的迭代。 But the function is failing to return FALSE when the selection is outside the named range.请参阅下面的“在这里失败”。谢谢。
使用 Visual Basic,我需要验证 Word 文档中的选择位置是否在指定范围内。许多年前,我使用这段代码来做到这一点:
ActiveDocument.Bookmarks("typdef").Select
While ((WordBasic.CmpBookmarks("\Sel", "typedef") = 8 _
Or WordBasic.CmpBookmarks("\Sel", "typedef") = 6 _
Or WordBasic.CmpBookmarks("\Sel", "typedef") = 10) _
And leaveloop <> 1
...
If WordBasic.CmpBookmarks("\Sel", "\EndOfDoc") = 0 Then
leaveloop = 1
End If
Wend
这是我写的更新函数:
Function FormatSpecHeadReturn(strStyle)
Dim rngBookmark As Word.Range
Dim rngSelection As Word.Range
Set rngBookmark = ActiveDocument.Bookmarks("SpecBodyPairRange").Range
Set rngSelection = Selection.Range
var = rngSelection.InRange(rngBookmark)
Debug.Print var
Do While rngSelection.InRange(rngBookmark) = True
Selection.Find.Style = ActiveDocument.Styles(strStyle)
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.HomeKey
' FAILING HERE: Returns TRUE when selection point
' is outside SpecBodyPairRange
var = rngSelection.InRange(rngBookmark)
Debug.Print var
Selection.HomeKey Unit:=wdLine, Extend:=wdMove
Selection.InsertBefore Chr(182)
Selection.EndKey
Selection.InsertAfter vbTab
Selection.MoveDown Unit:=wdLine, Count:=1, Extend:=wdMove
If rngSelection.InRange(rngBookmark) <> True Then Exit Do
Loop
End Function
我在当前项目中使用了 CmpBookmarks,但它不能可靠地返回当前位置的值。 When the selection point is within the named range, it returns 8 for two loops, and then returns 6. When the selection point is outside the named range, CmpBookmarks returns 6.
显然,CmpBookmarks 已被弃用。我找不到 CmpBookmarks 生成的返回值,也找不到现代等效函数。
我承认我不明白命名的“SpecBodyPairRange”范围和分配给 r 的范围之间的区别,这里:
按范围调暗
我可以看到这个例子中的“r”似乎包含了整个文档。我在 Microsoft.Office.Interop.Word 上研究了 Range Interface 和 Selection Interface,我还没有完全理解。我不是程序员,只是一个在某些编码方面自学成才的半技术作家,他的任务是自动化文档转换。
必须有更好的方法来比较选择点以验证它是否在命名范围内,但我找不到它。任何您能给我的指点都非常感谢!
【问题讨论】:
标签: vba ms-word named-ranges