''''''''''''直接定义给数组赋值'一维常量数组的定义Sub arrDemo1()Dim arr(2) As Variant '数组arr(0) = "vba"arr(1) = 100arr(2) = 3.14MsgBox arr(0)End Sub '二维常量数组的定义Sub arrDemo2()Dim arr(1, 1) As Variant 'Dim arr(0 To 1, 0 To 1) As Variantarr(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) NextNextEnd 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 arrarr = [{"a",10;"b",20;"c",30}]Range("a1:b3") = arrMsgBox Application.WorksheetFunction.VLookup("b", arr, 2, 0) '调用vlookup时可以作为第二个参数End Sub '动态数组的定义方法Sub arrDemo5()Dim arr1() '声明一个动态数组(动态指不固定大小)Dim arr2 '声明一个Variant类型的变量 arr1 = Range("a1:b2") '把单元格区域A1:B2的值装入数组arr1arr2 = Range("a1:b2") '把单元格区域A1:B2的值装入数组arr2 MsgBox arr1(1, 1) '读取arr数组中第1行第1列的数值MsgBox arr2(2, 2) '读取arr1数组的第2行第2列的数值End Sub
2、数组的赋值和计算
'读取单元格数据到数组,进行计算,再赋值给单元格Sub arr_calculate()Dim arr '声明一个变量用来盛放单元格数据Dim i%arr = Range("a2:d5") '把单元格数据搬入到arr里,它有4列4行For i = 1 To 4 '通过循环在arr数组中循环 arr(i, 4) = arr(i, 3) * arr(i, 2) '数组的第4列(金额)=第3列*第2例Next iRange("a2:d5") = arr '把数组放回到单元格中End Sub
3、数组的合并(join)与拆分(split)
'数组合并(join)与拆分(Split)Sub join_demo()Dim a As VariantDim b As Variant ' Join using spacesa = Array("Red", "Blue", "Yellow")b = Join(a, "")MsgBox ("The value of b is :" & b) 'Red Bule Yellow ' Join using $b = Join(a, "$") 'Red$Bule$YellowMsgBox ("The Join result after using delimiter is : " & b)End Sub Sub split_demo()Dim a As VariantDim b As Variant a = Split("Red$Blue$Yellow", "$") 'a = Array("red","blue","yellow") b = UBound(a) For i = 0 To b MsgBox a(i) NextEnd Sub
'利用数组获取所有工作表名称的自定义函数Function getSheetsname(id)Dim i%, arr()k = Sheets.CountReDim arr(1 To k)For i = 1 To k arr(i) = Sheets(i).NameNextgetSheetsname = Application.Index(arr, id)End Function
7、数组赋值,提高计算效率
'数组赋值,提高计算效率'2.03秒Sub dataInput()Dim start As Doublestart = TimerDim i&For i = 1 To 30000 Cells(i, 1) = iNextMsgBox "程序运行时间为" & Format(Timer - start, "0.00") & "秒"End Sub '0.12秒Sub dataInputArr()Dim start As Doublestart = TimerDim i&, arr(1 To 30000) As StringFor i = 1 To 30000 arr(i) = iNextRange("a1:a30000").Value = Application.Transpose(arr)MsgBox "程序运行时间为" & Format(Timer - start, "0.00") & "秒"End Sub '0.09秒Sub dataInputArr2()Dim start As Doublestart = TimerDim i&, arr(1 To 30000, 1 To 1) As StringFor i = 1 To 30000 arr(i, 1) = iNextRange("a1:a30000").Value = arrMsgBox "程序运行时间为" & Format(Timer - start, "0.00") & "秒"End Sub
社区
活动
资源
关于
腾讯云开发者
扫码关注腾讯云开发者
领取腾讯云代金券
热门产品
热门推荐
更多推荐
Copyright © 2013 - 2023 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号: 粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287