在其他模块中按字符串调用变量

时间:2019-04-28 12:19:19

标签: excel vba

我有一个用户表格,允许用户选择。选项应保存到关闭excel文件为止。在此之前,即使关闭用户表单,选项也将被记录。在用户表单中,我有11个复选框。

因此,我将11个全局变量放在“ sheet1”(重命名为数据库)模块下:

Public chk1Last As Boolean
Public chk2Last As Boolean
Public chk3Last As Boolean
Public chk4Last As Boolean
Public chk5Last As Boolean
Public chk6Last As Boolean
Public chk7Last As Boolean
Public chk8Last As Boolean
Public chk9Last As Boolean
Public chk10Last As Boolean
Public chk11Last As Boolean

然后我在一个类中使用以下代码将复选框状态记录到sheet1(重命名为DataBase)下的全局变量中:

Private Sub Chk_Change()
    Select Case Chk.Name
        Case "chk1"
            DataBase.chk1Last = Chk
        Case "chk2"
            DataBase.chk2Last = Chk
        Case "chk3"
            DataBase.chk3Last = Chk
        Case "chk4"
            DataBase.chk4Last = Chk
        Case "chk5"
            DataBase.chk5Last = Chk
        Case "chk6"
            DataBase.chk6Last = Chk
        Case "chk7"
            DataBase.chk7Last = Chk
        Case "chk8"
            DataBase.chk8Last = Chk
        Case "chk9"
            DataBase.chk9Last = Chk
        Case "chk10"
            DataBase.chk10Last = Chk
        Case "chk11"
            DataBase.chk11Last = Chk
    End Select
    'Do other things beneath'

在主模块中,我使用以下代码初始化用户表单”,如果首先加载了用户表单,则将启用所有复选框,如果未加载,则这些复选框将遵循租赁状态:

Private Sub UserForm_Activate()
    If Not DataBase.Activated Then
        For i = 1 To 11
            Controls("chk" & i) = True
        Next i
    Else
        chk1 = DataBase.chk1Last
        chk2 = DataBase.chk2Last
        chk3 = DataBase.chk3Last
        chk4 = DataBase.chk4Last
        chk5 = DataBase.chk5Last
        chk6 = DataBase.chk6Last
        chk7 = DataBase.chk7Last
        chk8 = DataBase.chk8Last
        chk9 = DataBase.chk9Last
        chk10 = DataBase.chk10Last
        chk11 = DataBase.chk11Last
    End If
    'Do other things beneath'

我想做的是简化类模块下的代码,如下所示:

在sheet1(重命名为数据库)中:

    Controls("DataBase." & Chk.name & "Last") = Chk

在main下使用for循环和controls()简化代码,如下所示:

Private Sub UserForm_Activate()
    If Not DataBase.Activated Then
        For i = 1 To 11
            Controls("chk" & i) = True
        Next i
    Else
        For i = 1 to 11
            Controls("chk" & i) = Controls("DataBase.chk" & i & "Last")
        Next i
    End If
    'Do other things beneath'

但是它失败了,如果我想通过controls()在其他模块中调用变量,正确的语法是什么?

非常感谢您的真诚帮助。

1 个答案:

答案 0 :(得分:0)

代替

Public chk1Last As Boolean
Public chk2Last As Boolean
'etc etc

使用:

Public ChkLast(1 to 11) As Boolean 

然后,您可以在与控件相同的循环中处理值。

您不能构建一个字符串来按名称寻址公共变量。如果变量是类实例中的属性,则可以执行某些操作,例如使用CallByName(),但是对于诸如此类的情况,数组更有意义,并且可以避免额外的麻烦。