Excel-宏与VBA-数组

数组

  1. 新方法
    LBound(myArray),一维数组最小角标,
    UBound(myArray),一维数组最大角标
    Option Base 1,修改默认最小角标为1,不修改默认为0
    LBound(myArray, 1),二维数组行的最小角标
    LBound(myArray, 2),二维数组列的最小角标
    UBound(myArray, 1),二维数组行的最大角标
    UBound(myArray, 2),二维数组列的最大角标
    ReDim myArray(1 To 3),重置动态数组的最大和最小角标,调整后之前赋值被抹除
    ReDim Preserve myArray(1 To 3),重置动态数组的最大和最小角标,调整后保存之前赋值

一维数组

  1. 基本使用案例
Option Explicit

Sub ArrayTest()
  ' 声明数组
  Dim myArray(1 To 3) As Integer
  ' Dim myArray(3) As Integer
  
  ' 为数组赋值
  myArray(1) = 0
  myArray(2) = 10
  myArray(3) = 20

  ' 访问数组值 输出 10
  MagBox myArray(2)

  ' 遍历数组
  For index = 1 To 3
    MsgBox myArray(index)
    Next index

  For index = LBound(myArray) To UBound(myArray)
    MsgBox myArray(index)
    Next index
End Sub

二维数组

  1. 基本使用案例
Option Explicit

Sub ArrayTest()
  ' 声明数组
  Dim myArray(1 To 2,1 To 2) As Integer
  ' Dim myArray(3) As Integer
  
  ' 为数组赋值
  myArray(1 , 1) = 0
  myArray(1 , 2) = 0
  myArray(2 , 1) = 10
  myArray(2 , 2) = 10

  ' 访问数组值 输出 10
  MagBox myArray(2, 1)

  ' 遍历数组
  For index_x = 1 To 2
    For index_y = 1 To 2
      MsgBox myArray(index_x, index_y)
       Next index_y
    Next index_x

  For index_x = LBound(myArray, 1) To UBound(myArray, 1)
    For index_y = LBound(myArray, 2) To UBound(myArray, 2)
      MsgBox myArray(index_x, index_y)
       Next index_y
    Next index_x
End Sub

动态数组

  1. 基本使用案例
Option Explicit
Sub myDynArray()
  ' 声明动态数组
  Dim myArray() As Integer
  ' 重置数组角标,不保留之前数据
  ReDim myArray(1 To 3)
  ' 重置数组角标,保留之前数据
  ReDim Preserve myArray(1 To 4)
End Sub
posted @ 2021-05-13 10:35  乔悟空  阅读(743)  评论(0编辑  收藏  举报