Class (Static) Methods in VBA

Viewed 72171

I wonder, whether it is possible to create class-methods in VBA. By class-method I mean methods that can be called without having an object of the class. The 'static'-keyword does that trick in C++ and Java.

In the example below, I try to create a static factory method.

Example:

'Classmodule Person'
Option Explicit
Private m_name As String
Public Property Let name(name As String)
    m_name = name
End Property
Public Function sayHello() As String
    Debug.Print "Hi, I am " & m_name & "!"
End Function

'---How to make the following method static?---'
Public Function Create(name As String) As Person
    Dim p As New Person
    p.m_name = name
    Set Create = p
End Function

'Using Person'
Dim p As New Person
p.name = "Bob"
p.sayHello 'Works as expected'
Set p2 = Person.Create("Bob") 'Yields an error'
8 Answers

That ("Public Shared") would only work in VB.Net.

There is no way to define Class Methods in VBA (or VB). I'd suggest to create a public function in a module.

AFAIK, the closest you can get (and it's not that close) is to use an "anonymous" instance, so something like this:

With New NotReallyStaticClass
    .PerformNotReallyStatic Method, OnSome, Values
End With

you have to declare p2 before you can use the Set as follows:

dim p2 as Person

Once you do this, you have to replace the Set statement using a standard assignment: p2 = Person.Create("Bob")

In the Function: remove the "Set" key word...this could also be the source of an error.

I'm flying blind, but logically it seems like this should work. I am new to using Class modules in VBA but they aren't too different from using VB.Net properties.

Related