Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

scope - Why can't the VBA Me keyword access private procedures in its own module?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...