oxw*_*der 1 excel vba excel-vba
我正在尝试创建一个具有多个属性的类,这些属性由我传入属性的相同数字索引.我已经尝试了几种代码配置,我最近的失败是这样的:
'dataTypeClass class module
Private ap() As String
Private dt() As String
Public Property Get apos(index As Long) As Variant
Set apos = ap(index)
End Property
Public Property Get dataType(index As Long) As Variant
Set dataType = dt(index)
End Property
Public Property Let apos(index As Long, apVal As String)
ap(index) = apVal
End Property
Public Property Let dataType(index As Long, dtVal As String)
dt(index) = dtVal
End Property
Run Code Online (Sandbox Code Playgroud)
我主要得到这个错误代码:
期望在下面的子项中使用下面的项目1获得"INT"和"".
Sub classTest()
Dim d As New dataTypeClass
d(1).dataType = "INT"
d(1).apos = ""
Debug.Print d(1).dataType & d(1).apos
End Sub
Run Code Online (Sandbox Code Playgroud)
我做错了几件事?
编辑:采取以下建议(如编辑我的问题而不是评论),我将变体设置为字符串,并使用let而不是set.由于我确实得到了超出范围的下标,我需要初始化类,但我需要redim index吗?如果每次运行脚本时索引的最大值不同,我该怎么办呢?
的apos属性1得到一个Variant在指定的index; 实现表明封装ap(index)是一个Object,所以返回类型可能应该Object代替Variant:
Public Property Get apos(index As Long) As Variant
Set apos = ap(index)
End Property
Run Code Online (Sandbox Code Playgroud)
setter使用Let赋值,这是hackish,但允许给定值Variant- 哦等不,它是一个String!
Public Property Let apos(index As Long, apVal As String)
ap(index) = apVal
End Property
Run Code Online (Sandbox Code Playgroud)
您收到此错误的原因是,正如错误所述,属性定义不一致.如果ap(index)是a String,则getter应如下所示:
Public Property Get apos(index As Long) As String
apos = ap(index)
End Property
Run Code Online (Sandbox Code Playgroud)
如果ap(index)是Object,则setter应如下所示:
Public Property Set apos(index As Long, apVal As Object)
Set ap(index) = apVal
End Property
Run Code Online (Sandbox Code Playgroud)
......和这样的吸气剂:
Public Property Get apos(index As Long) As Object
Set apos = ap(index)
End Property
Run Code Online (Sandbox Code Playgroud)
或者像这样:
Public Property Get apos(index As Long) As Variant
Set apos = ap(index)
End Property
Public Property Set apos(index As Long, apVal As Variant)
Set ap(index) = apVal
End Property
Run Code Online (Sandbox Code Playgroud)
换一种说法:
Property Let/ Property Set需要是相同的类型相同的名称的返回类型Property Get成员.Property Set用于分配.Property Let用于分配.Variant尽可能避免.Set用于指定除对象引用之外的任何内容.1所有这一切对于酒店也是如此dataType.