Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I use a private method inside the class in VBA?

Tags:

excel

vba

How Can I use a private method inside the class in VBA?

I wrote private procedure inside class

Private Sub setStartShift()

But I cannot call it in this way:

this.setStartShift
like image 431
Mr Tea Avatar asked Oct 24 '25 02:10

Mr Tea


1 Answers

TL;DR:

Use Me, not this, to access the current instance - but only the public interface is exposed through Me.

Use unqualified member calls to access the private interface.

Public Sub DoSomething()
    DoSomethingInternal ' implicit call
    'Call DoSomethingInternal '' explicit call (obsolete)
End Sub

Private Sub DoSomethingInternal() ' not accessible through public interface
    ' do stuff
End Sub

Why though?

In VBA, the essence of this is embodied in the Me implicit identifier: it refers to the current instance of the class, as exposed through its default interface. In other words if you're writing a method in a class module named Class1, then in that procedure Me refers to the current instance of Class1, as if you were accessing it from the outside:

Compile error: Method or data member not found

The specifications tell us how Me really works (emphasis mine):

Within the <procedure-body> of a procedure declaration that is defined within a <class-module-code-section> the declared type of the reserved name Me is the named class defined by the enclosing class module and the data value of Me is an object reference to the object that is the target object of the currently active invocation of the function.

Further, from section 5.3.1.5:

Each procedure that is a method has an implicit ByVal parameter called the current object that corresponds to the target object of an invocation of the method. The current object acts as an anonymous local variable with procedure extent and whose declared type is the class name of the class module containing the method declaration.

In other words when you do this:

Dim foo As Class1
Set foo = New Class1
foo.DoSomething 42

How the compiled code actually runs is closer to something like this:

Dim foo As Class1
Set foo = New Class1
Class1.DoSomething foo, 42

And since the parameter's type is the class name of the class module containing the method declaration, the member must exist on that class' Public interface for the member call to be resolvable at compile-time.

"Understanding 'Me' (no flowers, no bees)" on my "Rubberduck News" blog

like image 187
Mathieu Guindon Avatar answered Oct 26 '25 18:10

Mathieu Guindon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!