如何在MS-Word宏中检查段落是否在表中?

Dha*_*wal 6 vba ms-word

Word中的段落对象具有名为Range的属性.在此Range对象中有一个名为Cells的属性.

对于不在表中的段落,此属性Paragraph.Range.Cells设置为"".这可以在调试模式的Watches窗口中看到.

对于表中的段落,属性Paragraph.Range.Cells中包含其他属性,例如它具有一个名为Count的属性.

我使用Paragraph.Range.Cells的这个属性来确定段落是否在表中.但是,我似乎无法弄清楚如何测试这个.

例如,我不能简单地测试这样......

如果paragraph.Range.Cells <> Null Then ....甚至If IsNull(paragraph.Range.Cells)那么......

它会抛出运行时错误'5907'此位置没有表

那么,我该如何测试呢?谢谢

小智 11

您可以使用该Information属性:

If Selection.Information(wdWithInTable) Then
  'What ever you'd like to do
End If
Run Code Online (Sandbox Code Playgroud)

因此,您不需要任何手动错误捕获机制.


Gar*_*ill 9

除非段落在表中,否则不能调用Cells方法.您需要使用不同的方法来确定范围是否在表中.

你可以使用......

paragraph.Range.Tables.Count > 0
Run Code Online (Sandbox Code Playgroud)

...要么...

paragraph.Range.Information(wdWithinTable)
Run Code Online (Sandbox Code Playgroud)

请注意,第二个看起来更明显,但实际上更慢(如果您在循环中执行此操作,则只会出现问题).


Ahm*_*mad 1

*编辑 (if Err=) 更改为 (If Err<>)

您可以简单地允许错误发生并使用OnError语句捕获它

Dim ParagraphIsTable As Object

    OnError Resume Next        'allows errors to happen but execute next instruction
    ParagraphIsTable = paragraph.Range.Cells

  If Err <> 5907 Then '(this is to check for a specific error that might have happened)
          'No Error occured, this means that ParagraphIsTable variable must contain a value
          ' Do the rest of your code here
    Else
          ' an Error occured, this means that this is not a table
          ' do whatever
    End If
OnError Goto 0          ' This cancels the effect of OnError Resume Next
                  ' Which means if new errors happen, you will be prompt about them
Run Code Online (Sandbox Code Playgroud)