真的很新,自学成才会很感激任何帮助
已将电子表格中的范围分配给数组,但它会启动数组第1行中的数据。
Dim arr As Variant
arr = Range("DATA")
有没有办法从第0行开始? 提前致谢
答案 0 :(得分:2)
范围操作很慢,最好是使用临时数组,然后在更改起始位置时复制到另一个数组。 确实阵列 - > array =非常快
Dim arr, arr2 As Variant
arr2 = Range("DATA").value2
redim arr(0 to ubound(arr2)-1, 0 to ubound(arr2,2)-1)
for i= 0 to ubound(arr2)-1
for j= 0 to ubound(arr2,2)-1
arr(i,j)= arr2(i+1,j+1)
next
next
答案 1 :(得分:0)
那么,如果你要清理范围派生的VBA数组,为什么不在你处理列范围或行范围的情况下使它们成为1维而不是错误的2维?以下是作为默认值并且也使用0作为默认值,但提供了覆盖两个默认值的方法:
Function RangeToArray(R As Range, Optional b As Long = 0, Optional collapse As Boolean = True) As Variant
'returns a b-based array of the values in R
'if the Range is 1-dimensional and collapse is true, the array returned is 1-dimensional
Dim i As Long, j As Long, m As Long, n As Long, k As Long
Dim vals As Variant, arr As Variant
m = R.Rows.Count
n = R.Columns.Count
If m = 1 And n = 1 Then 'to catch an edge-case
ReDim vals(1 To 1, 1 To 1)
vals(1, 1) = R.Value
Else
vals = R.Value
End If
If collapse And (m = 1 Or n = 1) Then
k = Application.WorksheetFunction.Max(m, n)
ReDim arr(b To b + k - 1)
For i = 1 To k
If m = 1 Then
arr(b + i - 1) = vals(1, i)
Else
arr(b + i - 1) = vals(i, 1)
End If
Next i
Else
ReDim arr(b To b + m - 1, b To b + n - 1)
For i = 1 To m
For j = 1 To n
arr(b + i - 1, b + j - 1) = vals(i, j)
Next j
Next i
End If
RangeToArray = arr
End Function
它将像A = RangeToArray(Range("A1:B3"))