VBA 中的类(静态)方法 [英] Class (Static) Methods in VBA

查看:41
本文介绍了VBA 中的类(静态)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 VBA 中创建类方法.通过类方法,我的意思是可以在没有类对象的情况下调用的方法.'static' 关键字在 C++ 和 Java 中起到了这个作用.

I wonder, whether it is possible to create class-methods in VBA. By class-method I mean methods that can be called without having an object of the class. The 'static'-keyword does that trick in C++ and Java.

在下面的示例中,我尝试创建一个静态工厂方法.

In the example below, I try to create a static factory method.

示例:

'Classmodule Person'
Option Explicit
Private m_name As String
Public Property Let name(name As String)
    m_name = name
End Property
Public Function sayHello() As String
    Debug.Print "Hi, I am " & m_name & "!"
End Function

'---How to make the following method static?---'
Public Function Create(name As String) As Person
    Dim p As New Person
    p.m_name = name
    Set Create = p
End Function

'Using Person'
Dim p As New Person
p.name = "Bob"
p.sayHello 'Works as expected'
Set p2 = Person.Create("Bob") 'Yields an error'

推荐答案

那个(公共共享")只能在 VB.Net 中工作.

That ("Public Shared") would only work in VB.Net.

没有办法在 VBA(或 VB)中定义类方法.我建议在模块中创建一个公共函数.

There is no way to define Class Methods in VBA (or VB). I'd suggest to create a public function in a module.

这篇关于VBA 中的类(静态)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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