我的变量:answer_a, answer_b, answer_c, question_letter
该变量question_letter
由用户设置。根据他们是否输入a
、b
或c
,我想分别获得answer_a
、answer_b
或answer_c
。
因为以后会有明显多于三个的answer_
变量,所以我想做这样的事情:answer_ & question_letter
,但这不会编译。
我怎样才能做到这一点?谢谢!
有几种方法可以做到这一点。一种可能是使用 case 语句:
Select Case question_letter
Case a
code
Case b
more code
Case else
code if nothing matches
End Select
一个简单的解决方案是数组:
Dim answer() as String ' An empty array
ReDim answer(1 to 3) ' Set the array to 3 "cells"
Dim ansReturn as String
...
Select Case question_letter
case "a"
ansReturn = answer(1)
case "b"
ansReturn = answer(2)
case "c"
ansReturn = answer(3)
case else
ansReturn = ""
End Select
您可以将数组设置为任意(正整数)大小。
Tools -> References 并添加Microsoft Scripting Runtime。这将允许您使用将 ket 与值相关联的字典;
Private answers As Dictionary
Sub callMeAtStartup()
'// setup answers
Set answers = New Dictionary
answers.Add "a", "111"
answers.Add "b", "222"
answers.Add "c", "333"
End Sub
Function lookup(char As String) As String
If answers.Exists(char) Then lookup = answers(char)
End Function
Sub test()
callMeAtStartup
'....
Dim answer As String
answer = lookup("f")
If Len(answer) Then MsgBox "Its " & answer
End Sub
作为 26 个或更少选项的替代方案,将字母映射到数组索引
dim answers(3) as String
answers(0) = "111" '//a
answers(1) = "222"
answers(2) = "333" '//c
question_letter = "b"
'//char to index
index = asc(ucase$(question_letter)) - 65
if index < ubound(answers) Then
msgbox answers(index)
end if