2011-06-22 33 views
5

Word中的段落對象有一個名爲Range的屬性。在這個Range對象中有一個名爲Cells的屬性。如何在MS-Word宏中檢查段落是否在表格中?

對於不在表格中的段落,此屬性Paragraph.Range.Cells設置爲「」。這可以在調試模式下的Watches窗口中看到。

對於表中的段落,Paragraph.Range.Cells屬性具有其他屬性,例如它具有一個名爲Count的屬性。

我使用Paragraph.Range.Cells的這個屬性來確定段落是否在表中。但是,我似乎無法弄清楚如何測試這個。

例如,我不能簡單地測試這樣的...

如果paragraph.Range.Cells <>空值,則....甚至 如果ISNULL(paragraph.Range.Cells)然後...

它拋出一個運行時錯誤「5907」有在這個位置

因此,沒有桌子,我會怎麼測試呢?感謝

+0

請參閱下面的答案,以及後面編輯的具體Err = 5907。 – Ahmad

回答

1

* 編輯(如果ERR =)改爲(如果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 
+1

+1甚至很難看起來像你有你的評論混合起來。 '如果Err = 5907然後'沒有錯誤發生......實際上,確實發生了錯誤5907。 –

+0

非常感謝您的通知。 – Ahmad

+0

在閱讀您的評論後,我確實糾正了它。再次感謝,merci boucoup – Ahmad

6

發生,趕上它,你可以」除非段落在表中,否則請調用Cells方法。您需要使用其他方法來確定範圍是否在表中。

您可以使用...

paragraph.Range.Tables.Count > 0 

......或者......

paragraph.Range.Information(wdWithinTable) 

注意,第二個看起來更明顯,但實際上是慢(只有當問題你在循環中做這個)。

+0

'paragraph.Range.Tables.Count> 0'做到了(即使在Word Interop中.Net):) – JanDotNet

10

可以使用Information property

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

因此,你不需要任何手動錯誤捕獲機制。