tags:

views:

4026

answers:

4

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'
+6  A: 

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.

Thomas

+2  A: 

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
Mike Woodhouse
A: 

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.

+2  A: 

Bit late in the day but what the heck

There are no class or static methods in VB6/VBA. But you can explicity state the name of a module. You can't have a module and a class of the same name but you could call it something similar.

So I could have a class called Employee and a module called EmployeeUtil and then I can write:

  Dim emp As Employee
  Dim code As String
  Set emp = EmployeeUtil.Create( "Smith", "John", 21-Feb-1988)
  code = "123XY"
  If EmployeeUtil.IsCodeValid( code) Then
    emp.Code = code
  Else
    emp.Code = EmployeeUtil.DefaultCode
  EndIf

Yes, the values are hard coded and the code handling should probably be under the property setter but that is not the point I'm trying to make. EmployeeUtil is essentially being a place holder for non-instance members.

You'll note that the Create method this way gives us a pseudo like constructor for the Employee class. All that function does is create an instance of Employee, assign the parameters via the property setters and then returns the instance. If your constructing instances of objects in a lot of places, then this can save a lot of code.

Swanny