数组的最高填充元素
您可以在循环中后退一步,直到找到第一个不为空的数组元素。
这相当于“最后一个”填充元素。
简答:
Function HighestPopIdx(ByRef arr) As Long
For HighestPopIdx = UBound(arr) To LBound(arr) Step -1
If Not IsEmpty(arr(HighestPopIdx)) Then Exit Function
Next
End Function
更长的答案:
要获得数组中填充最多的元素,我将使用 For..Next 循环和 IsEmpty 功能。
(为了演示,这个例子有点过于复杂了。)
Sub demo() '(Hit CTRL+G in the VBE to view the output in the Immediate window.)
'Make a test ARRAY of 5 elements:
Dim arr(1 To 5)
Erase arr '(just to make sure the test is starting 'fresh')
arr(1) = "X"
arr(2) = 99
arr(4) = "Y" '3 of the 5 elements have data (highest one is 4)
Dim elIdx As Long, highestPopEl As Long
For elIdx = LBound(arr) To UBound(arr)
If Not IsEmpty(arr(elIdx)) Then highestPopEl = elIdx
Next elIdx
Debug.Print "The highest populated element index is " & highestPopEl 'Returns 4
End Sub
...或相反(根据您的情况,第一个示例可能更快。
其他说明:
除了@jtolle 的answer,Count 和CountA 工作表函数都不起作用:
With Application.WorksheetFunction
Debug.Print "Array WS CountA", .CountA(arr) 'returns 5 (Counts cells)
Debug.Print "Array WS Count", .Count(arr) 'returns 1 (Counts numbers)
End With
...进一步到 cmets,表明数组和单元格范围的功能相似,但 不 相同:
'Make a test RANGE of 5 cells
Dim rge As Range
Set rge = Range("A1:A5")
rge.Clear '(maker sure we're starting fresh)
Range("A1") = "X"
Range("A2") = 99
Range("A4") = "Y" '3 of the 5 cells have data
With Application.WorksheetFunction
Debug.Print "Range WS CountA", .CountA(rge) 'returns 3 (Counts values)
Debug.Print "Range WS Count", .Count(rge) 'returns 1 (Counts numbers)
End With
'... and the VBA [Range.Count] method behaves differently:
Debug.Print "Range VBA .Count", rge.Count 'returns 5 (Counts cells)
另一方面,如果我的“实际”目标是对数组中的每个元素做一些事情,我会使用 For..Each 循环和 IsEmpty功能。
'if my actual purpose is to ***do something*** to an ARRAY...
Debug.Print: Debug.Print "Array [For..Next] :"
Dim elCnt As Long, el
For Each el In arr
If Not IsEmpty(el) Then _
elCnt = elCnt + 1: Debug.Print "#" & elCnt & ": Element value =", el
Next el ' (returns "X", 99, "Y")
'...and the identical method can be used on a RANGE of cells
Debug.Print: Debug.Print "Range [For..Next] :"
Dim clCnt As Long, cl
For Each cl In rge
If Not IsEmpty(cl) Then _
clCnt = clCnt + 1: Debug.Print "#" & clCnt & ": Cell value =", cl
Next cl ' (returns "X", 99, "Y")
End Sub
完整输出:
The highest populated element index is 4.
Array WS CountA 5
Array WS Count 1
Range WS CountA 3
Range WS Count 1
Range VBA .Count 5
Array [For..Next] :
#1: Element value = X
#2: Element value = 99
#3: Element value = Y
Range [For..Next] :
#1: Cell value = X
#2: Cell value = 99
#3: Cell value = Y
更多信息: