按名称获取VBA集合中的项目

嗨,

我正在尝试通过在VBA Excel中引用它的名称属性来执行自定义集合中的自定义对象。 我发誓它之前(或至less没有发生错误),现在它的kaput。 当我尝试通过stringGet某些内容时,我收到invalid call or argument错误。 提前感谢甚至阅读这个,任何帮助表示赞赏。 <\编辑>

这里是收集:

 Option Explicit Private DRAFields As New Collection Sub Add(Name As String, Optional colNbr As Long, Optional Exists As Boolean) Dim fld As New DRAFld fld.colNbr = colNbr fld.Name = Name fld.Exists = Exists DRAFields.Add fld End Sub Property Get Item(NameOrNumber As Variant) Set Item = DRAFields(NameOrNumber) '<------- Error here End Property 

通过将一个名称数组传递给一个函数来添加项目,并且集合返回时没有问题。 我可以通过使用密钥来迭代。 但是,如果得到这样的错误: Debug.Print myFlds.Item("Customer").colNbr

对象类以防万一:

 Option Explicit Private clmNbrPvt As Long Private namePvt As String Private existsPvt As Boolean Public Property Get colNbr() As Long colNbr = clmNbrPvt End Property Public Property Let colNbr(lngParam As Long) clmNbrPvt = lngParam End Property Public Property Get Name() As String Name = namePvt End Property Public Property Let Name(strParam As String) namePvt = strParam End Property Public Property Get Exists() As Boolean Exists = existsPvt End Property Public Property Let Exists(booParam As Boolean) existsPvt = booParam End Property 

为什么不是这个function:

 Function validateAndBuildDRAFields(ByRef arrReqFields() As String, _ inputSheet As Worksheet, _ Optional VBAModule As String) As clsDRAFields Dim lEndCol As Long: lEndCol = Standard.zGetLastColumn(inputSheet, 1) Dim i As Long Dim x As Long Dim intExit As Long Dim myDRAFields As New clsDRAFields Set validateAndBuildDRAFields = myDRAFields 'Builds myDRAFields items from arrReqFields For i = LBound(arrReqFields) To UBound(arrReqFields) myDRAFields.Add arrReqFields(i) Next i 'checks if required fields exist on input sheet 'if found then sets column number and exists = true For i = 1 To myDRAFields.Count For x = 1 To lEndCol If inputSheet.Cells(1, x) = myDRAFields.Item(i).Name Then myDRAFields.Item(i).colNbr = x myDRAFields.Item(i).Exists = True intExit = intExit + 1 Exit For End If Next x If intExit = UBound(arrReqFields) + 1 Then Exit For Next i ' tells user if there are any missing fields and ends if true If (Not intExit = UBound(arrReqFields) + 1) Or _ intExit = 0 Then For i = 1 To myDRAFields.Count If myDRAFields.Item(i).Exists = False Then Call Standard.TheEndWithError("I couldn't find the " & myDRAFields.Item(i).Name & _ " column in your file. Please add " & myDRAFields.Item(i).Name & _ " to your DRA Layout.", False, VBAModule) End If Next i Set myDRAFields = Nothing Standard.TheEnd End If End Function 

要通过密钥访问收集项目,必须在将项目添加到集合时提供密钥。 关键是可选的。 使用string访问集合项目时,Item方法假定您要匹配键。 当你使用一个整数时,它假设你想要位置索引。

因此,请将您的Add方法中的行更改为

 DRAFields.Add fld, fld.Name 

您可以通过其名称属性访问项目。