I just discovered that the Me keyword cannot access private procedures even when they are inside its own class model.
Take the following code in Class1:
Private Sub Message()
Debug.Print "Some private procedure."
End Sub
Public Sub DoSomething()
Me.Message
End Sub
This code instantiates an instance of the class:
Sub TestClass()
Dim objClass As New Class1
objClass.DoSomething
End Sub
Me.Message
throws compile error "Method or data member not found."
If I change Private Sub Message()
to Public
the procedure works fine. I can also remove the Me keyword from the DoSomething procedure, but I was under the impression that the idea behind the Me keyword is to ensure that multiple instances of Class1 are properly encapsulated.
Why can't the VBA Me keyword access procedures in its own module when they are private? Is it safe to omit the Me keyword and do something like this in a class?
Private Sub Message()
Debug.Print "Some private procedure."
End Sub
Public Sub DoSomething()
Message
End Sub
Thanks!
Update: Thanks for the tips on proper syntax, my code is working. I am still looking for an explanation of why Me can reference private procedures in an instance of it's own module. I couldn't find any good documentation.
Any guess as to why it was designed that way would be pure supposition without talking to the designers. But my own guess is this, the Me
keyword returns a reference to the object the code is currently executing in. I would guess rather than create a special case for Me
, they found it easier to continue to obey rules of scope for an object. Which is to say object.method
can only work on public or friend methods. So Me
, is exactly what it says, an instance of the currently executing object. And since VBA/VB6 doesn't have shared methods, it doesn't really matter if you prefix with Me
or not.
But if it makes you feel any better, I find it incredibly obnoxious too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With