Dim so(1 To 3) As Double
so(1) = 1
so(2) = 2
so(3) = 3
MsgBox UBound(so, 1)
For iSo = 1 To UBound(so, 1)
MsgBox so(iSo)
Next iSo
* Cách viết hàm có tham số truyền vào là array
Dim prices(1 To 10, 1 To 100) As Double
Cách xem tổng số phần tử trong biến mảng VBA Excel
MsgBox UBound(prices, 1) ' so phan tu trong mang 1
MsgBox UBound(prices, 2) ' so phan tu trong mang 2
Ví dụ:
Dim so(1 To 3, 1 To 2) As String
' bien nay co 3 dong, 2 cot
' a b
' c d
' e f
' dong 1
so(1, 1) = "a"
so(1, 2) = "b"
' dong 2
so(2, 1) = "c"
so(2, 2) = "d"
' dong 3
so(3, 1) = "e"
so(3, 2) = "f"
soDong = UBound(so, 1)
soCot = UBound(so, 2)
For iDong = 1 To soDong
For iCot = 1 To soCot
MsgBox so(iDong, iCot)
Next iCot
Next iDong
Đoạn lệnh lấy vùng chọn ra biến Array
Dim r As Range
Set r = Range("H10:I12")
arr = r ' đổi biến Range sang biến Array
sodong = UBound(arr, 1) ' so dong
socot = UBound(arr, 2) ' so cot
' in toàn bộ giá trị biến Array
For iDong = 1 To sodong
For iCot = 1 To socot
MsgBox arr(iDong, iCot)
Next iCot
Next iDong
Ví dụ tạo biến mảng:
Dim so(1 To 2, 1 To 3) As Integer
so(1, 1) = Cells(1, 1)
so(1, 2) = Cells(1, 2)
so(1, 3) = Cells(1, 3)
so(2, 1) = Cells(2, 1)
so(2, 2) = Cells(2, 2)
so(2, 3) = Cells(2, 3)
soDong = UBound(so, 1)
soCot = UBound(so, 2)
For iDong = 1 To soDong
For iCot = 1 To soCot
MsgBox so(iDong, iCot)
Next iCot
Next iDong
Dim s As String
s = "Xanh,Do,Vang,Tim"
Dim arr() As String
arr = Split(s, ",")
For i = 1 To UBound(arr)
Msgbox arr(i,1)
Next
Ví dụ A-Z biến mảng trong VBA Excel