使用变量A的值来获得变量B.

时间:2013-07-16 14:20:47

标签: vba variables excel-vba excel

我的变量:answer_a, answer_b, answer_c, question_letter

变量question_letter由用户设置。根据他们是否输入abc,我想分别获得answer_aanswer_banswer_c。< / p>

因为稍后会有超过三个answer_变量,我想做类似这样的事情:answer_ & question_letter,但这不会编译。

我该怎么做?谢谢!

3 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。一种可能是使用案例陈述:

Select Case question_letter
    Case a
        code
    Case b 
        more code
    Case else
        code if nothing matches
End Select

答案 1 :(得分:0)

一个简单的解决方案是数组:

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

您可以将数组设置为任意(正整数)大小。

答案 2 :(得分:0)

工具 - &gt;引用并添加 Microsoft Scripting Runtime 。这将允许您使用将ket与值相关联的Dictionary;

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