包含基于ToC的代码?

时间:2016-06-03 21:26:05

标签: word-vba

这是关于如何实现我的代码的一般性问题,而不是代码本身的问题。

我有一些代码可以扫描Word文档,查找某些单词,并将它们放入索引中。本文档可能有也可能没有目录。

如果有ToC,我希望我的宏跳过该范围内的文字,所以我有这样的一行:

Sub find_things()
Dim myDoc as Word.Document
Dim otherVariables here

[some preliminary code]

' the next line checks to see if the current range is in a ToC
  If rngXE.InRange(myDoc.TablesOfContents(1).Range) = False Then
      [code here will find my text, and do some things]
  End If 
End Sub

所以,希望您可以看到如果rngXE范围不在目录中,请运行一些代码。

但是,由于有时没有ToC,我在If语句行引发了错误。 ("集合中请求的成员不存在")。

问题:处理此问题的最佳方法是什么?我之前应该On Error Resume Next吗?因此,如果出现错误,它会继续吗?

或者,有没有办法计算目录,如果它是0,那么包括If语句行?

Sub find_things()
Dim myDoc as Word.Document
Dim otherVariables here

[some preliminary code]

' the next line checks to see if the current range is in a ToC
  If myDoc.TablesofContents.Count > 0 Then    
      If rngXE.InRange(myDoc.TablesOfContents(1).Range) = False Then
          [code here will find my text, and do some things]
      End If 
 End If
End Sub

...除非我使用此功能,否则始终会在没有TOC的情况下跳过我的代码。我不想使用On Error Goto,因为我已经深入了解GoTo通常是一个坏主意......但这可能是最佳选择,不是吗? / p>

我希望这一点很清楚 - 有点难以表达问题,但如果我能澄清任何事情,请告诉我!

编辑:我现在处理此问题的方式是,如果我收到错误,我只会注释掉If rngXE.InRange(myDoc...) = False和相应的End If行,并且运行完美。我正在寻找一种自动的方法,而不是我的个人干预。

1 个答案:

答案 0 :(得分:1)

您可以使用的两个相当简单的模式,无需使用“On Error Goto”或“Goto”:

If myDoc.TablesofContents.Count = 0 Then
  call asubtodothework(rngXE) ' you may need to pass more parameters...
elseif not rngXE.InRange(myDoc.TablesOfContents(1).Range)
  call asubtodothework(rngXE) ' ditto
end if

Dim bDoIt As Boolean
bDoIt = True
If myDoc.TablesofContents.Count > 0 Then
  If rngXE.InRange(myDoc.TablesOfContents(1).Range) Then
    bDoIt = False
  End If
End If
If bDoIt Then
  ' do the work
End If

(正如他们所说的那样,两者都与现有代码做出相同的假设,即你只需要检查TableOfContents(1)。我的猜测是,如果你需要检查更多的ToC,那么你最终会得到一些一些代码而不是像第二种模式一样。)

甚至以下......

Dim bDoIt As Boolean
bDoIt = True
If myDoc.TablesofContents.Count > 0 Then
  bDoIt = rngXE.InRange(myDoc.TablesOfContents(1).Range) 
End If
If bDoIt Then
  ' do the work
End If

...或者也许是单线程工作(我实际上没有检查逻辑,我个人倾向于使用完整的If ... End If构造)...

Dim bDoIt As Boolean
bDoIt = True
If myDoc.TablesofContents.Count > 0 Then bDoIt = rngXE.InRange(myDoc.TablesOfContents(1).Range)
If bDoIt Then
  ' do the work
End If
相关问题