为什么VBA Me关键字不能在其自己的模块中访问私有过程? [英] Why can't the VBA Me keyword access private procedures in its own module?

查看:59
本文介绍了为什么VBA Me关键字不能在其自己的模块中访问私有过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现Me关键字即使在私有过程中也无法访问私有过程。

I just discovered that the Me keyword cannot access private procedures even when they are inside its own class model.

在Class1中添加以下代码:

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 引发编译错误未找到方法或数据成员。

Me.Message throws compile error "Method or data member not found."

如果我更改了将私人子消息()转换为公共,该过程即可正常运行。我也可以从DoSomething过程中删除Me关键字,但给我的印象是Me关键字背后的想法是确保正确封装Class1的多个实例。

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.

为什么私有的VBA Me关键字访问过程不能在其自己的模块中访问?可以安全地省略Me关键字并在类中执行类似的操作吗?

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

谢谢!

更新:感谢正确语法的提示,我的代码正在运行。我仍在寻找为什么的解释,我可以在其自身模块的实例中引用私有过程。我找不到任何好的文档。

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.

推荐答案

关于它为何以这种方式设计的任何猜测都是纯假设,无需讨论给设计师。但是我自己的猜测是, Me 关键字返回对当前正在执行代码的对象的引用。我猜想而不是为 Me ,他们发现继续遵守对象的作用域规则变得更加容易。也就是说 object.method 只能在公共或朋友方法上工作。所以 Me 就是它所说的,它是当前正在执行的对象的实例。而且由于VBA / VB6没有共享方法,因此是否以 Me 为前缀并不重要。

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.

这篇关于为什么VBA Me关键字不能在其自己的模块中访问私有过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆