2009-06-18 115 views
1

在某些附加到Excel 2003電子表格的VBA中,我需要使用一些需要一段時間才能實例化的對象 - 所以我只想執行一次'設置'的事情...如何知道對象是否已被引用?

這更容易顯示代碼比寫一個解釋!

' Declare the expensive object as global to this sheet 
Dim myObj As SomeBigExpensiveObject 

Private Sub CommandButtonDoIt_Click() 

    ' Make sure we've got a ref to the object 
    If IsEmpty(myObj) Then ' this doesn't work! 
     Set myObj = New SomeBigExpensiveObject 
    End If 

    ' ... etc 

End Sub 

如何檢查myObj是否已設置?

我試過IsNull(myObj)和IsEmpty(myObj) - 無論myObj的狀態如何都跳過'set'。我不能做

if myObj = Nil then 

if myObj = Empty then 

if myObj = Nothing then 

任何想法?

SAL

+0

您是否嘗試過CreatObject? – THEn 2009-06-18 16:54:10

+0

這個頁面有關於VB/VBA中空,空和空白之間差異的很好的信息http://beta.blogs.msdn.com/ericlippert/archive/2003/09/30/53120.aspx – Lunatik 2009-06-19 05:31:14

回答

6

這應該工作:

If myObj IS Nothing Then 

(注意是「IS」),如果還是不行,那麼就必須通過類具體實現異步intialization因爲COM初始化調用是同步的默認。因此,您需要檢查文檔,或與開發人員討論Big類的某些屬性或同步方法,以供您等待。

相關問題