VBA-用类实现数组扩容

我们知道数组的长度是固定的,定义了以后不能随意的增加其长度,但是我们可以用类来实现表面上的扩容(即增加数组的存储空间)

1.首先我们添加一个类模块,取名为”myarr”

并且在里面添加一些方法(比如扩容,查看数组值等)

具体代码如下:

Option Explicit
Private arr() As String '数组 ,用来存储数据
Private ilen As Integer '数组长度
Private icount As Integer '实际数组长度
Private Const per As Integer = 4 '每次扩容的个数(可变)
'容量,只读属性
Property Get length() As Integer
    length = ilen

End Property
'实际数据的个数,只读属性
Property Get count() As Integer
    Dim i As Integer
    For i = 1 To UBound(arr)
        If Len(arr(i)) = 0 Then
        icount = i - 1
        count = icount
        Exit Property
    End If
    Next i
    icount = length
    count = icount
End Property
'添加数据
Sub add(item As String)
   If count = length Then '实际个数达到了容量,应该扩容
        Call expandarr
   End If
   arr(count + 1) = item
  
End Sub

'获取全部数据
Function getallvalue() As String()
    Dim ar() As String, i As Integer
    ReDim ar(1 To count) As String
     For i = 1 To count
         ar(i) = arr(1)
     Next i
    getallvalue = ar
   
End Function
'获取数据
Function getvalue(index As Integer) As String
    If index > length Or index < 1 Then
        getvalue = "小标越界"
    Else
        getvalue = arr(index)
    End If
   
End Function
'扩容(步进式扩容
Sub expandarr()
    ilen = ilen + per
    ReDim Preserve arr(1 To ilen) As String
End Sub

Private Sub Class_Initialize()
 Call expandarr
End Sub

2.我们来测试一下

Option Explicit
Sub 测试()
   Dim myar As myarr
   Set myar = New myarr
   Debug.Print myar.length & "....." & myar.count
   myar.add "坦克"
   myar.add "克"
   myar.add "坦克lo"
   myar.add "坦"
   myar.add "坦克合伙人和健康"
   myar.add "坦克是哦"
     Debug.Print myar.length & "....." & myar.count
End Sub

效果如下图所示

我们可以看出,当数组的容量不够时,数组会自动扩容(表面上增加四个存储空间)


猜你喜欢

转载自blog.csdn.net/qq_41777527/article/details/81025950