我的代码的想法是我想在一个数组中存储行号,其中是文本"AnchorPointStartDontDelete"
代码
Set rightRng = Range(Cells(8, 10), Cells(ER.row - 1, 10))
Dim arr() As Long
ReDim arr(1 To 1) As Long
For Each rng In rightRng
If rng.value = "AnchorPointStartDontDelete" Then
ReDim Preserve arr(1 To UBound(arr) + 1) As Long
Debug.Print rng.row
arr(UBound(arr)) = rng.row
End If
Next rng
我的范围的 Debug.Print rng.row
如下所示,但我无法理解零值的来源,因为rng
来自row 8 to ER.Row
0 8 11 13 14 16 18 22 26 33 34 36 38 40 43 46 41 46
更正代码 - >将零值作为数组中的最后一个,然后删除它。
For Each rng In rightRng
If rng.value = "AnchorPointStartDontDelete" Then
arr(UBound(arr)) = rng.row
ReDim Preserve arr(1 To UBound(arr) + 1) As Long
End If
Next rng
' Code line below delete the last value
ReDim Preserve arr(1 To UBound(arr) - 1) As Long
答案 0 :(得分:0)
你从一个1元素的数组开始,所以在进入循环之前,你有arr(1) = 0
。然后你第一次进入循环并立即增加arr
的大小,所以现在ubound(arr) = 2
并将第一次命中的行写入元素2。
你应该避免做太多Redim Preserve
,因为它非常昂贵。
以下代码减少了Redims的数量。
Const size = 100
Dim arr() As Long, cnt As Long
ReDim arr(1 To size)
cnt = 0
For Each rng In rightRng
If rng.Value = "AnchorPointStartDontDelete" Then
cnt = cnt + 1
If cnt > UBound(arr) Then ReDim Preserve arr(1 To UBound(arr) + size)
arr(cnt) = rng.Row
End If
Next rng
ReDim Preserve arr(1 To cnt)