Is there a way to overload the constructor / initialize procedure for a class in VBA?

前端 未结 4 887
时光取名叫无心
时光取名叫无心 2020-12-11 04:37

In C#, I know that I can overload the constructor for a class by specifying it in the body of the class:

public class MyClass()
{
    public MyClass(String s         


        
4条回答
  •  误落风尘
    2020-12-11 05:31

    As Jtolle indicated, this is simply not possible in VBA/VB6. There is no perfect way to work around this but, what I personally do is create a Public/Friend sub call Initialize with the parameters I want (in VBA/VB6 you use "Optional" parameters for overloading) and then put a quick check in all exposed members of the class that throws an exception if you try to access them without running the initialize method. A basic example might look like this:

    Option Explicit
    
    Private m_blnInitialized As Boolean
    Private m_lngID As Long
    Private m_strFirstName As String
    
    Public Sub Initialize(ByVal ID As Long, Optional ByVal someOtherThing As String = vbNullString)
        If m_blnInitialized Then Me.Clear
        m_lngID = ID
        m_strFirstName = SomeLookUp()
        If LenB(someOtherThing) Then
            ''Do something here.
        End If
        m_blnInitialized = True
    End Sub
    
    Public Property Get ID() As Long
        If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
        ID = m_lngID
    End Property
    
    Public Property Get FirstName() As String
        If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
        FirstName = m_strFirstName
    End Property
    
    Private Function SomeLookUp() As String
        ''perform magic on Me.ID
    End Function
    
    Public Sub LoadPicture()
        If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
        ''More magic
    End Sub
    
    Public Sub Clear()
        If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
        m_strFirstName = vbNullString
        m_lngID = 0&
        m_blnInitialized = False
    End Sub
    

    It's not great, but it's about as good as it's going to get with VBA/VB6.

提交回复
热议问题