我循环遍历命名范围并根据单元格是否为空来追加数组。我对VBA中的数组不太熟悉,所以也许我的逻辑不正确。代码会一直覆盖数组中的第一个元素,并且永远不会增加。我不确定为什么即使将一个元素分配给第一个索引后,UBound(myArray)仍然保持为0。
我的代码类似于:
Dim myArray() As Double
ReDim Preserve myArray(0)
For Each cell In [myRange]
If cell <> "" Then
If UBound(myArray) > 0 Then
ReDim Preserve myArray(0 To UBound(myArray) + 1)
End If
myArray(UBound(myArray)) = cell.value
End If
Next
答案 0 :(得分:8)
使用变量并递增它,如果变量在代码完成时大于ubound,则没有区别:
Sub Test()
Dim myArray() As Double, X As Long
X = 0
ReDim Preserve myArray(X)
For Each cell In Range("Hello")
If cell <> "" Then
ReDim Preserve myArray(0 To X)
myArray(X) = cell.Value
X = X + 1
End If
Next
End Sub
答案 1 :(得分:3)
将If UBound(myArray) > 0 Then
更改为可以解决问题的UBound(myArray) >= 0 Then
。
Sub Test()
Dim myArray() As Double
ReDim Preserve myArray(0)
For Each cell In Range("Hello")
If cell <> "" Then
If UBound(myArray) >= 0 Then
myArray(UBound(myArray)) = cell.Value
ReDim Preserve myArray(0 To UBound(myArray) + 1)
End If
End If
Next
End Sub
答案 2 :(得分:0)
扩展Dan Donoghue的解决方案以避免过多的redim(对于Jeanno的解决方案,通过使用变量进行过多的重新计算),我会使用
Dim rng as Range
Set rng = Range("Hello")
Dim myArray() As Double, X As Long, N As Long
X = 0
N = WorksheetFunction.CountIf(rng, "<>")
ReDim Preserve myArray(X)
For Each cell In rng
If cell <> "" And X < N Then
myArray(X) = cell.Value
X = X + 1
If X < N Then ReDim Preserve myArray(0 to X)
End If
Next