我有:
Collection
” users
Class
” MatchClass
实例组成
MatchClass
” 仅包含两个属性-userid
和matchArray
(以及一些与问题无关的方法) 在Collection
上循环,同时能够
matchArray
(已排序)中找出最高值并存储userid
以Collection
循环遍历For Each
Dim users as New Collection Dim i as Byte Dim max as Integer: max = 0 Dim maxuser as String ' users Collection is filled with instances of MatchClass ' ... skipping code to simplify ... Dim user as MatchClass For Each user in users temp = user.matchArray(0, 0) If temp > max Then max = temp maxuser = users.Item ' <- this won't work End If Next user
然后我无法访问
user
循环中For Each
的位置
或者我尝试了数值循环:
For i = users.Count to 1 Step -1 users.Item(i).matchArray(0, 0) ' <- this won't work Next i
不幸的是,这也不起作用,因为我无法访问属性
MatchClass
代码中的users.Item(i)
个实例。
也许我能同时做到两全其美? 感觉应该是我刚想念的那种随意性。
答案 0 :(得分:1)
根据我的评论,我希望这两种方法都能起作用。很高兴被证明是错误的,因为他们未经测试...
对于每个人
Dim users As New Collection
Dim i As Byte
Dim max As Integer: max = 0
Dim maxuser As String
' users Collection is filled with instances of MatchClass
' ... skipping code to simplify ...
Dim user As MatchClass
Dim lngIndex As Long
For Each user In users
lngIndex = lngIndex + 1
temp = user.matchArray(0, 0)
If temp > max Then
max = temp
maxuser = lngIndex
End If
Next user
对于
Dim user As MatchClass
For i = users.Count To 1 Step -1
Set user = users.item(i)
matchArray = item.matchArray(0, 0)
Next i
如果我理解了您的问题,那么我会以为以上两种情况(如果不是全部)都能为您带来理想的结果。
答案 1 :(得分:1)
MatchClass
是对象,而users
是MatchClass
实例的集合,那么您应该使用Set
关键字来分配对象引用(我指的是maxuser = users.Item ' <- this won't work
这行-但此行还有另一个问题(如下所述)。Dim maxuser as String
毫无意义,除非您有没有的字符串集合。Item
对象的Collection
成员需要一个索引或最初用于将该项目添加到集合中的键。我无法对此进行测试(所以我自己可能是错的),但是我的看法是:
Private Sub FindMaxUser()
Dim users As New Collection
Dim i As Byte
Dim max As Long: max = 0
Dim temp As Long
' ... skipping code to simplify ...
Dim user As MatchClass
Dim maxuser As MatchClass ' <- Shouldn't be a string.
For Each user In users
temp = user.matchArray(0, 0)
If temp > max Then
max = temp
Set maxuser = user ' <- MatchClass is an object. "Set" keyword is required for object references
End If
Next user
End Sub
此处的主要更改是将maxuser
声明为MatchClass
,并在循环内使用Set
(找到新的最大值时)。