使用Excel VBA对复选框的可变标题

时间:2019-02-12 17:03:38

标签: excel vba userform

我有以下代码,这些代码根据记录集(可以是A,B,C或D)中的值创建复选框。 我希望复选框标题显示这些字母的含义。例如,A =优秀,B =很好,C =很好,D =不好。 我在工作表中具有这些值,并执行vlookup获取相应的名称,因此代码当前正在执行所需的操作,但是有没有办法不在工作表中(可能在变量或隐藏工作表中)具有这些值?

If Not rst.EOF And Not rst.BOF Then
    i = 0
    Do
        With MultiPage1.Pages(2).Controls.Add("Forms.Checkbox.1", "Checkbox" & i)
            .Top = yPos
            .Left = 7
            .Caption = Application.WorksheetFunction.VLookup(rst![Perspect], ThisWorkbook.Sheets("Sheet1").Range("b26:c30"), 2, False)
            .Width = 450
            .Height = 24
            .WordWrap = True
            .Value = False
            yPos = yPos + 17
            .Tag = rst![Perspect]
            i = i + 1
            rst.MoveNext
        End With
    Loop Until rst.EOF
    rst.Close
End If

4 个答案:

答案 0 :(得分:1)

类似的事情可能会帮助

Function getVal(strLetter As String)

Dim a() As Variant

Dim b() As Variant

a = Array("Gold", "Silver", "Bronze")
b = Array("A", "B", "C")

Debug.Print Application.WorksheetFunction.Index( _
                a, 1, _
                Application.WorksheetFunction.Match(strLetter, b, 0))
End Function

这样打电话

getVal("B")给出银,getVal("C")给出青铜,等等

答案 1 :(得分:1)

最好的选择是将其放入您的记录集。如果您没有该选项,那么我认为这是最干净的方法:

.Caption = ...替换为

 .Caption = GradeCaption(rst![Perspect])

然后创建您的函数:

Function GradeCaption(Grade As String) As String
    Select Case Grade
        Case "A"
            GradeCaption = "Excellent"
        Case "B"
            GradeCaption = "Very Good"
        Case "C"
            GradeCaption = "Good"
        Case "D"
            GradeCaption = "Bad"
    End Select
End Function

答案 2 :(得分:1)

有很多方法可以实现您的目标:一个工作表,一个隐藏工作表,数组,一个字典...附带一个选择用例的可能性:

SELECT * FROM MOVIES

答案 3 :(得分:1)

对于这些类型的问题,始终是词典的爱好者。 我可以建议。

Sub GradeDictionary()
Dim dict As Object, key, val
Set dict = CreateObject("Scripting.Dictionary")

key = "A": val = "Excellent"
dict.Add key, val

key = "B": val = "Very Good"
dict.Add key, val

key = "C": val = "Good"
dict.Add key, val

key = "D": val = "Bad"
dict.Add key, val

For Each k In dict.Keys
    ' Print key and value
    Debug.Print k, dict(k)
Next

End Sub