[英]Variable caption on checkboxes using excel VBA
我有以下代码根据记录集(可以是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
这样的事情可能会有所帮助
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")
提供铜等
最好的选择是将其放入记录集中。 如果您没有该选项,那么我认为这是最干净的方法:
将.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
有很多方法可以实现您的目标:一个工作表,一个隐藏工作表,数组,一个字典...附带一个选择用例的可能性:
Sub Call_GetDescr()
MsgBox "A: " & getDescription("A")
MsgBox "B: " & getDescription("B")
MsgBox "C: " & getDescription("C")
MsgBox "D: " & getDescription("D")
MsgBox "X: " & getDescription("X")
End Sub
Function getDescription(inputStr As String) As String
Dim result As String
Select Case inputStr
Case "A"
result = "very good"
Case "B"
result = "good"
Case "C"
result = "sufficient"
Case "D"
result = "bad"
Case Else
result = "not defined"
End Select
getDescription = result
End Function
一直是这类问题的词典迷。 我可以建议。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.