vba 如何在vba中创建公共/共享实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4329428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:22:19  来源:igfitidea点击:

How to create common/shared instance in vba

vba

提问by Gadolin

I would like to create one instance of class that all other could use so far I create each instance in each class that needes its methods.

我想创建一个所有其他类都可以使用的类实例,到目前为止我在每个需要其方法的类中创建了每个实例。

Is there a way that I could create only one instance which would be seen by other classes.

有没有一种方法可以让我只创建一个其他类可以看到的实例。

Normaly I could create some sort of static variable that would be seen by others. But it seems not possible in VBA :/

通常我可以创建一些其他人可以看到的静态变量。但在 VBA 中似乎不可能:/

回答by RolandTumble

In a Module:

在一个模块中:

Private objSharedClass As myClass

Public Function GetShared() As myClass

    If objSharedClass Is Nothing Then
        Set objSharedClass = New myClass
    End If

    Set GetShared = objSharedClass

End Function

It's the VB(A) implementation of the Singleton pattern. You need to consider carefully whether or not it's really appropriate, and if so, that's the way to do it. When I use it, I usually put the above code in a Module by itself (except that if I'm using more than one Singleton in the application I put them all together in a single Module). You can add a destruction routine to the same module and call it from your application exit:

它是单例模式的 VB(A) 实现。你需要仔细考虑它是否真的合适,如果合适,那就是这样做的方法。当我使用它时,我通常将上面的代码单独放在一个模块中(除非我在应用程序中使用多个单例,我将它们全部放在一个模块中)。您可以向同一个模块添加销毁例程并从应用程序出口调用它:

Public Sub CloseSingleton()

    Set objSharedClass = Nothing

End Sub

Or you can just let it go out of scope when the app closes--not as tidy, but I've never seen it cause a problem (I usually do clean up, though...).

或者你可以在应用程序关闭时让它超出范围 - 不是那么整洁,但我从未见过它引起问题(不过我通常会清理......)。

EDIT

编辑

Usage (just in case it's not obvious). Either:

用法(以防万一它不明显)。任何一个:

...
Set objLocalCopy = GetShared
DoSomethingWith objLocalCopy.MethodOrProperty
...

Or:

或者:

...
DoSomethingWith GetShared.MethodOrProperty
...

The first is preferable if you're going to use the shared class more than once in the calling routine, but the second works fine for a single call.

如果您要在调用例程中多次使用共享类,则第一个更可取,但第二个对于单个调用工作正常。

回答by N0Alias

Make the sub or function in a Module and you'll be able to access it from your other classes.

在 Module 中创建 sub 或 function,您将能够从其他类访问它。

ModuleName.MethodName