VBA-导入名称空间? [英] VBA - Import namespaces?

查看:98
本文介绍了VBA-导入名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在VBA中导入名称空间?我正在写Word宏,我想将所有函数放在模块或类中.但是一旦这样做,我就会发现我无法轻松访问VBA表单中的控件.我必须先包含表单的名称,然后在该表单中访问控件.我不能只是去

Is it possible to import namespaces in VBA? I'm writing Word macros and I want to put all functions inside Modules or Classes. But once I do that I see that I cannot reach the controls in the VBA form easily. I have to include the name of the form first, then access the control within that one. I can't just go

TextBox1.Caption

我必须走

Form1.TextBox1.Caption

有没有办法解决这个问题?

Is there a way to get around this?

推荐答案

您不应该如此紧密地耦合类/模块.辅助模块不需要了解Form1类,因为这样就不能在另一个项目中单独使用它.

You shouldn't be coupling your classes/modules so tightly. A worker module shouldn't require knowledge of the Form1 class, because then it can't be used separately in another project.

相反,您可能希望将其执行工作的自变量传递给助手类中的函数,然后返回结果(如有必要).作为一个完全无用的琐碎示例:

Instead, you probably want to pass the function in your helper class an argument on which it performs work, and then returns the result (if necessary). As a completely useless, trivial example:

Public Sub SetLabelText(ByVal lbl As Label, ByVal caption As String)
    lbl.Caption = caption
End Sub

您将在表单类中调用它,就像这样:

And you would call it from within the form class, like so:

MyHelpers.SetLabelText(Label1, "New Label Caption")

这样,您可以使用 any 形式的帮助器类中的函数.

That way, you can use the functions in your helper class from any form.

但是,就您的实际问题而言,不. VBA没有任何命名空间"的概念.最好的办法是With语句,但是正如我上面所讨论的,频繁执行此操作很可能表明存在设计缺陷.

But, as far as your actual question, no. VBA doesn't have any concept of "namespaces". The best you can do is the With statement, but having to do this frequently is more likely an indication of a design flaw, as I discussed above.

这篇关于VBA-导入名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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