VBA给数组赋值的方法有以下几种:
=
号将一个数组赋值给另一个数组。Dim arr1() As Integer
Dim arr2() As Integer
arr1 = Array(1, 2, 3) ' 将数组 {1, 2, 3} 赋值给 arr1
arr2 = arr1 ' 将 arr1 的值赋值给 arr2
Dim arr(4) As Integer
Dim i As Integer
For i = 0 To 4
arr(i) = i + 1 ' 将每个元素赋值为对应的序号
Next i
Dim arr() As Integer
arr = Array(1, 2, 3, 4, 5) ' 将数组常量 {1, 2, 3, 4, 5} 赋值给 arr
Dim arr() As String
Dim str As String
str = "apple,banana,orange"
arr = Split(str, ",") ' 将字符串按逗号拆分为数组赋值给 arr
Dim arr() As Variant
Dim rng As Range
Set rng = Worksheets("Sheet1").Range("A1:C3")
arr = rng.Value ' 将区域 A1:C3 的值赋值给 arr
注意:在VBA中,数组的赋值是通过引用传递的,即两个数组变量指向同一个存储空间。如果想要将一个数组的值复制给另一个数组,可以使用Array函数创建一个新的数组,并将原数组的值复制给新数组。