1 数组旳大小
Lbound(数组)可以获取数组的最小下标
Ubound(数组)可以获取数组的最大上标
Ubound(数组,1)可以获取数组的行方面最大上标
Ubound(数组,2)可以获取数组的列方向最大上标
2 动态数组的动态扩充
2.1一维数组的扩充
如果一个数组无法或者不方便计算出总的大小,而在一些特殊情况下又不允许有空位,这时我们就需要用动态的导入方法
Private Sub ComboBox1_GotFocus()
Dim arr(), x, arr1, k
arr1 = Range("a1:a10")
For x = 1 To UBound(arr1)
If arr1(x, 1) > 10 Then
k = k + 1
ReDim Preserve arr(1 To k)
arr(k) = arr1(x, 1)
End If
Next x
ComboBox1.List = arr
End Sub
运行有问题,暂时没发现
2.2 二维数组的扩充
Sub t11()
Dim arr, arr1()
arr = Range("a1:d6")
Dim x, k
For x = 1 To UBound(arr)
If arr(x, 1) = "B" Then
k = k + 1
ReDim Preserve arr1(1 To 4, 1 To k) '应该是K行四列,把行当成列,把列当成行。在列的方向扩充。
arr1(1, k) = arr(x, 1)
arr1(2, k) = arr(x, 2)
arr1(3, k) = arr(x, 3)
arr1(4, k) = arr(x, 4)
End If
Next x
Range("a8").Resize(k, 4) = Application.Transpose(arr1) '行列转置
End Sub
这样扩充的方法比较难以掌握。可以用以下的方法
Sub d8()
Dim arr, arr1(1 To 1000, 1 To 4)
arr = Range("a1:d6")
Dim x, k
For x = 1 To UBound(arr)
If arr(x, 1) = "B" Then
k = k + 1
arr1(k, 1) = arr(x, 1)
arr1(k, 2) = arr(x, 2)
arr1(k, 3) = arr(x, 3)
arr1(k, 4) = arr(x, 4)
End If
Next x
Range("a15").Resize(k, 4) = arr1
End Sub
3 清空数组
把原来数据清除掉重新装
erase arr1
Sub d9()
Dim arr, arr1(1 To 1000, 1 To 1)
Dim x, m, k
arr = Range("a1:a16")
For x = 1 To UBound(arr)
If arr(x, 1) <> "" Then
k = k + 1
arr1(k, 1) = arr(x, 1)
Else
m = m + 1
Range("c1").Offset(0, m).Resize(k) = arr1
Erase arr1 '数组清空,重新装数据
k = 0 'k也需要初始一下,k是计数器
End If
Next x
End Sub