|
本帖最后由 q3698995 于 2024-8-12 11:59 编辑
今天用类模块写了一个永久保存全局变量的案例
分享给大家。
注意key和value仅支持字符串或数字的格式。
类模块代码:
- Option Explicit
- Private d As Object
- Private ws As Worksheet
- Private arr()
- Private r&
- Private Sub Class_Initialize(): Dim i&: Set d = CreateObject("scripting.dictionary"): Set ws = 基本信息: With ws: On Error Resume Next: .ShowAllData: r = .Columns("A:B").Find("*", , , , , 2).Row: arr = .Columns("A:B").Value2: End With: For i = 1 To r: d(arr(i, 1)) = i: Next: End Sub
- Public Sub Add(ByVal key As Variant, ByVal item As Variant): Dim i&, b As Boolean: i = d(key): b = i = 0: r = r - b: i = IIf(b, r, i): arr(i, 1) = key: arr(i, 2) = item: d(key) = i: ws.Range("A" & i & ":B" & i).Value2 = Array(key, item): End Sub
- Public Property Get Exists(ByVal key As Variant) As Boolean: Exists = d.Exists(key): End Property
- Public Property Get Items() As Variant: Dim v As Variant, i&: v = d.Items: i = UBound(v): ReDim brr(0 To i): For i = 0 To i: brr(i) = arr(v(i), 2): Next: Items = brr: End Property
- Public Property Get Keys() As Variant: Keys = d.Keys: End Property
- Public Sub Remove(ByVal key As Variant): Dim i&, b As Boolean: i = d(key): b = i = 0: r = r + Not b: i = i + b: On Error Resume Next: arr(i, 1) = Empty: arr(i, 2) = Empty: d.Remove key: With ws: .Range("A" & i & ":B" & i).Value2 = "": End With: End Sub
- Public Sub RemoveAll(): d.RemoveAll: With ws: .Columns("A:B").Value2 = "": arr = .Columns("A:B").Value2: End With: r = 0: End Sub
- Public Property Get Count&(): Count = d.Count: End Property
- Public Property Get item(ByVal key As Variant) As Variant: On Error Resume Next: item = arr(d.item(key), 2): End Property
- Private Sub Class_Terminate(): Set d = Nothing: Set ws = Nothing: End Sub
复制代码 标准模块调用测试:
- Option Explicit
- Private o As Object
- '字典有的方法基本都有,不一一举例,注意key和value仅支持字符串或数字的格式
- Sub ReadyObj()
- If o Is Nothing Then Set o = New GlobalVar
- End Sub
- Sub 保存全局变量()
- ReadyObj
- o.RemoveAll '清空全局变量
- o.Add "a", 1 '添加全局变量a,后期改变a的值可以用o.Add "a", 3 方法覆盖原值
- o.Add "b", 2 '添加全局变量
- End Sub
- Sub 删除全局变量()
- ReadyObj
- o.Remove "a" '删除全局变量
- End Sub
- Sub 判断全局变量是否存在()
- ReadyObj
- Debug.Print "变量a是否存在返回结果:" & o.Exists("a") '检查变量是否存在
- Debug.Print "变量b是否存在返回结果:" & o.Exists("b") '检查变量是否存在
- Debug.Print "变量c是否存在返回结果:" & o.Exists("c") '检查变量是否存在
- End Sub
- Sub 打印所有变量()
- Dim i&
- ReadyObj
- i = o.Count
- Debug.Print "变量个数为" & i & "个:"
- For i = 1 To i '输出所有变量
- Debug.Print "变量" & o.Keys()(i - 1) & "的值为:" & o.Items()(i - 1)
- Next
- End Sub
复制代码
|
评分
-
2
查看全部评分
-
|