我需要检查许多数组中每个元素的条件。我想优化它到一个循环。那可能吗。我已经检查了数组数组和数组集合的代码,但是我一直遇到类型不匹配错误。 代码:
Private Function RowNo(ByVal text1 As String) As Long
Dim f As Range
Set f = Columns(2).Find(text1, Lookat:=xlWhole)
If Not f Is Nothing Then
RowNo = f.Row
Else
RowNo = 0
End If
End Function
Q1 = "1."
YtQ1Ar = Array("1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.7.1", "1.7.2", _
"1.7.3", "1.7.4", "1.7.5", "1.7.6", "1.7.7", "1.7.8", "1.7.9", "1.7.10", "1.7.11", "1.7.12", _
"1.7.13", "1.7.14", "1.7.15", "1.7.16", "1.7.17", "1.7.18", "1.7.19", "1.7.20", "1.7.21", "1.7.22", _
"1.7.23", "1.7.24", "1.8", "1.9", "1.10", "1.11", "1.12", "1.13")
NtQ1Ar = Array("1.1")
Dim ArColl As Collection
Set ArColl = New Collection
ArColl.Add YtQ1Ar
ArColl.Add NtQ1Ar
ArColl.Add Q1
Dim xColl As Variant
Dim rColl As Long
Dim X As Long
For X = 1 To ArColl.Count
xColl = ArColl.Item(X)
For Each xColl In ArColl
rColl = RowNo(xColl)
If rColl = 0 Then
Debug.Print "'" & xColl & "' was not found!"
End If
Next xColl
Next X
如何循环遍历许多数组的每个元素?
答案 0 :(得分:1)
到目前为止,我所知道的唯一方法是一个自称为“
”的子Public ArColl() As Variant 'in Module
Sub ArrayRunner(ParamArray SArray() As Variant)
Dim holder, runner
For Each holder In SArray
If IsArray(holder) Then
For Each runner In holder
ArrayRunner runner
Next
Else
If Not IsMissing(holder) Then
Debug.Print holder 'print every element
'put all values in one long array
ArColl(UBound(ArColl)) = holder
ReDim Preserve ArColl(UBound(ArColl) + 1)
End If
End If
Next
End Sub
也改变
Dim ArColl As Collection
Set ArColl = New Collection
ArColl.Add YtQ1Ar
ArColl.Add NtQ1Ar
ArColl.Add Q1
For X = 1 To ArColl.Count
xColl = ArColl.Item(X)
For Each xColl In ArColl
rColl = RowNo(xColl)
If rColl = 0 Then
Debug.Print "'" & xColl & "' was not found!"
End If
Next xColl
Next X
到
Redim ArColl(0)
ArrayRunner(Array(YtQ1Ar, NtQ1Ar, Q1))
For X = 0 To ubound(ArColl) - 1
If RowNo(ArColl(X)) = 0 Then
Debug.Print "'" & ArColl(X) & "' was not found!"
End If
Next X