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函數創建一個新的數組,并將原數組的值復制給新數組。