简体   繁体   English

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

[英]How to check if a Paragraph is in a Table or not in MS-Word macro?

The paragraph object in the Word has a property called Range. Word中的段落对象具有称为范围的属性。 Within this Range object has a property called Cells. 在此Range对象内具有一个称为Cells的属性。

For paragraph that are not in a table, this property Paragraph.Range.Cells is set to "". 对于不在表中的段落,此属性Paragraph.Range.Cells设置为“”。 This can be seen in the Watches window in debug mode. 这可以在“监视”窗口中的调试模式下看到。

For paragraph that are in a table, the property Paragraph.Range.Cells has other properties in it, for example it has a property called Count. 对于表中的段落,属性Paragraph.Range.Cells中具有其他属性,例如,它具有称为Count的属性。

I am using this property of Paragraph.Range.Cells to determine if the paragraph is in a table or not. 我正在使用Paragraph.Range.Cells的此属性来确定该段落是否在表中。 However, I cant seem to figure out how to test this. 但是,我似乎无法弄清楚如何进行测试。

For example, I cannot simply test like this... 例如,我不能简单地像这样测试...

If paragraph.Range.Cells <> Null Then.... or even If IsNull(paragraph.Range.Cells) Then ... 如果para..Range.Cells <>为Null,则....甚至是IsNull(paragraph.Range.Cells)则为...

It throws a Run-time error '5907' There is no table at this location 它将引发运行时错误“ 5907”。此位置没有表

So, how would I test for this? 那么,我将如何测试呢? thanks 谢谢

You can use the Information property : 您可以使用Information属性

If Selection.Information(wdWithInTable) Then
  'What ever you'd like to do
End If

Hence you don't need any manual error catching mechanisms. 因此,您不需要任何手动错误捕获机制。

You can't call the Cells method unless the paragraph is in a table. 除非段落在表中,否则您不能调用Cells方法。 You need to use a different method to determine whether the range is in a table. 您需要使用其他方法来确定范围是否在表中。

You can use either... 您可以使用...

paragraph.Range.Tables.Count > 0

...or... ...要么...

paragraph.Range.Information(wdWithinTable)

Note that the second one looks more obvious, but is actually slower (only a problem if you're doing this inside a loop). 请注意,第二个看起来更明显,但实际上要慢一些(如果您在循环内执行此操作,只会出现问题)。

* Edited (if Err=) changed to (If Err<>) *已编辑(如果Err =)更改为(如果Err <>)

You can simply allow the error to happen and catch it using OnError statement 您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM