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

查看:27
本文介绍了为什么 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."

如果我将 Private Sub Message() 更改为 Public,则程序运行正常.我也可以从 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天全站免登陆