2013-05-28 95 views
1

我是一個具有foo類的例程。類foo包含類欄,但不會初始化它。在我的例程中,我將父類方法的foo的類欄作爲對象傳入。接收方法然後將foo的酒吧初始化爲新酒吧。通過方法初始化子類

由於某些原因,當我稍後引用foo時,bar未初始化。無論如何,在另一種方法中初始化foo的酒吧?

<Class Foo> 
Option Explicit 

Public mybar As Bar 

<Class Bar> 
Option Explicit 

Public theText As String 

<Main Module> 
Public Sub Test() 
    Dim myfoo As New foo 
    Dim abar As Bar 


    Derp myfoo.mybar 


    myfoo.mybar.theText = "Test" 
End Sub 

Public Sub Derp(ByRef mybar As Bar) 
    Set mybar = New Bar 

End Sub 

當代碼遇到myfoo.mybar.thetext =「Test」時,我收到錯誤91,對象變量或With塊變量未設置。

我使用VBA通過供應商特定的系統,VBA版本6.5.1054。

回答

1

爲了讓你的代碼工作,你需要做很小的改進。您需要在foo class內完全初始化bar class。因此,而不是這一行:

Public mybar As Bar 

變化成這樣:

Public mybar As New Bar 

不過,也有一些提高你的Main Module。因此,我就是這麼做的,它的工作原理:

Public Sub Test() 
    Dim myfoo As New foo 
    Dim abar As New Bar 

    myfoo.mybar.theText = "Test" 
End Sub 

如果你需要保持Derp子那麼你abar variable必須是公開的。

在評論之後編輯 現在我對你的需求有了更好的理解,所以我會建議這樣解決它。

  1. 保持不變bar class
  2. Foo class需要額外的方法,它允許在需要時進行初始化​​。完整Foo class代碼:

    Option Explicit 
    
    Public mybar As Bar 
    
    Sub BarInit() 
        Set mybar = New Bar 
    End Sub 
    
  3. Main module應該比看起來像下面的代碼(看看評論小組內):

    Public Sub Test() 
    
    
        Dim myfoo As New Foo 
    
        'this will not work at this stage, _ 
        kept to show the problem, Error 91, _ 
        please remove it after test 
        myfoo.mybar.theText = "test" 
    
        'initialize Bar class within Foo class _ 
        using Foo class method 
        myfoo.BarInit 
    
        'now will work as it's initialized 
        myfoo.mybar.theText = "test" 
        Debug.Print myfoo.mybar.theText 
    End Sub 
    

正如你所看到的初始化仍然保持內foo class但只有在需要時才調用BarInit method

+0

我有意不在foo內初始化bar,因爲在某些情況下,bar不存在,我測試它是否是無用的。 Foo實際上包含三個不同的小節,我希望能夠推廣一些可以在所有三個小節中調用的方法,方法是傳遞相應的小節。看起來這可能是不可能的。 – lfrandom

+0

這是可能的...在編輯後查看我的答案。 –