VBA数组用法案例详解

  ''''''''''''直接定义给数组赋值

  '一维常量数组的定义

  Sub arrDemo1()

  Dim arr(2) As Variant '数组

  arr(0) = "vba"

  arr(1) = 100

  arr(2) = 3.14

  MsgBox arr(0)

  End Sub

  '二维常量数组的定义

  Sub arrDemo2()

  Dim arr(1, 1) As Variant 'Dim arr(0 To 1, 0 To 1) As Variant

  arr(0, 0) = "apple"

  arr(0, 1) = "banana"

  arr(1, 0) = "pear"

  arr(1, 1) = "grape"

  For i = 0 To 1

  For j = 0 To 1

  MsgBox arr(i, j)

  Next

  Next

  End Sub

  ''''''''''''用array函数创建常量数组

  '一维数组

  Sub arrayDemo3()

  Dim arr As Variant '数组

  arr = Array("vba", 100, 3.14)

  MsgBox arr(0)

  End Sub

  '二维数组

  Sub arrayDemo4()

  Dim arr As Variant '数组

  arr = Array(Array("张三", 100), Array("李四", 76), Array("王五", 80))

  MsgBox arr(1)(1)

  End Sub

  '调用Excel工作表内存数组

  ' 一维数组[{"A",1,"C"}]

  '二维数组[{"a",10;"b",20;"c",30}]

  Sub mylook()

  Dim arr

  arr = [{"a",10;"b",20;"c",30}]

  Range("a1:b3") = arr

  MsgBox Application.WorksheetFunction.VLookup("b", arr, 2, 0) '调用vlookup时可以作为第二个参数

  End Sub

  '动态数组的定义方法

  Sub arrDemo5()

  Dim arr1() '声明一个动态数组(动态指不固定大小)

  Dim arr2 '声明一个Variant类型的变量

  arr1 = Range("a1:b2") '把单元格区域A1:B2的值装入数组arr1

  arr2 = Range("a1:b2") '把单元格区域A1:B2的值装入数组arr2

  MsgBox arr1(1, 1) '读取arr数组中第1行第1列的数值

  MsgBox arr2(2, 2) '读取arr1数组的第2行第2列的数值

  End Sub