美文网首页
3.5.7声明动态数组

3.5.7声明动态数组

作者: linglin123 | 来源:发表于2019-01-08 00:01 被阅读0次

    在使用public或Dim语句声明数组时,不能使用变量来声明数组的尺寸。

    Sub Test()
    Dim a As Integer '将a定义为int型变量'
    a = Application.WorksheetFunction.CountA(Range("A:A"))
    Dim arr(1 To a) As String '通过变量a来定义数组的尺寸,这是一种错误的做法'
    End Sub
    
    

    如图所示


    动态数组错误声明.jpg

    为解决这一问题,可将数组声明为动态数组,声明方法如下所示

    Sub 声明动态数组()
    Dim a As Integer
    '用工作表函数counta求A列中非空单元格的个数,将结果保存在变量a中'
    a = Application.WorksheetFunction.CountA(Range("A:A"))
    Dim arr() As String '定义一个String类型的动态数组arr'
    ReDim arr(1 To a) '重新定义数组arr的大小'
    End Sub
    

    声明时不定义数组的大小,即维数不确定,可存储数据个数不确定
    定义为动态数组后,可使用Redim语句来重新定义数组的大小,但不能改变数组的类型

    其他创建数组方法
    1、使用Array函数声明数组

    Sub usearray()
    Dim arr As Variant
    arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    MsgBox "arr数组的第2个元素为:" & arr(1)
    End Sub
    

    2、使用Split函数创建数组

    Option Explicit
    Sub SplitTest() 'Split函数用于字符串'
    Dim a As Variant
    a = Split("东东,林林,彬彬,狗屎", ",") '将字符串用,进行拆分,第二个参数为分隔符,
    然后将拆分后的字符串以一个索引号为0的一维数组保存到a中'
    MsgBox "the 2nd element of the array a is :" & a(1)
    
    End Sub
    

    Split函数返回的总是一个索引号从0开始的一维数组

    3、通过单元格区域直接创建数组

    Sub Rngarr()
    Dim a As Variant
    a = Range("A1:C3").Value
    Range("E1:G3").Value = a
    End Sub
    

    相关文章

      网友评论

          本文标题:3.5.7声明动态数组

          本文链接:https://www.haomeiwen.com/subject/mtrmrqtx.html