views:

216

answers:

2

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.

+3  A: 

You do not need the Me keyword to call inside own class.

Mitch Wheat
+1  A: 

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 an 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.

Oorang
Makes sense. Seems like `Me` is shorthand for hypothetically creating an object variable (`Dim Me As Object`) and setting that variable to the object that the code is in (`Set Me = ThisModule`. That object variable would still access module properties and procedures from the outside. Thanks!
Kuyenda