VBA自定义数据类型 - 默认值

时间:2013-12-11 19:04:28

标签: vba

我想在VBA中定义自定义数据类型,并为属性分配默认值。

示例:

Public Type Fruit
    Name as String
    Color as String
    Amount as Integer 'Default 12
End Type

Public Sub UseFruit
    Dim Banana as Fruit
    Banana.Name = "Banana"
    Banana.Color = "Yellow" 
    Debug.Print Banana.Amount
End Sub

我想在sub的最后一行打印12;即。如果我剔除水果,默认金额是十几个,除非我另有说明。

如何实现这一目标?提前谢谢!

2 个答案:

答案 0 :(得分:2)

除非你愿意把它变成一个Const,否则最好的方法是让一个函数为你生成“默认”Fruit。

为了演示Const,以下是有效的,但当然不能改变(这不再是有效的VBA ):

Public Type Fruit
    Name As String
    Color As String
    Const Amount As Integer = 12
End Type

由于您需要默认值,但必须是可修改的,我建议使用函数生成默认的Fruit:

Public Type Fruit
    Name As String
    Color As String
    Amount As Integer
End Type

Public Sub UseFruit()
    Dim Banana As Fruit
    Banana = getDefaultFruit
    Banana.Name = "Banana"
    Banana.Color = "Yellow"
    Debug.Print Banana.Amount 'Prints 12
End Sub

Public Function getDefaultFruit() As Fruit
    getDefaultFruit.Amount = 12 'Default 12
End Function

答案 1 :(得分:0)

另一种方法是使用类模块而不是类型声明。

  

在名为Fruit的类中

Public Name as String 
Public Color as String 
Public Amount as Integer

Private Sub Class_Initialize()
    Amount = 12
end sub
  

在模块中

Public Sub UseFruit()
Dim Banana as New Fruit
    Banana.Name = "Banana"
    Banana.Color = "Yellow" 
    Debug.Print Banana.Amount
End Sub

在具有许多子功能或更大VBA项目的模块中,这将是更明确的解决方案,而不是使用Type。