根据用户输入评估变量

时间:2017-05-11 15:34:06

标签: vba excel-vba excel

来自Python,我无法找到实现最终目标的方法,因为Excel VBA中不存在类似eval()的函数。

以下是我尝试使用一个可以扩展的简单示例:

Dim userinput as String
userinput = inputbox("A=John, B=Kate, C=Tim", "Enter a letter that corresponds with your name: ")
Dim A as String
Dim B as String
Dim C as String

A = John
B = Kate
C = Tim

Dim Phrase as Variant
phrase = msgbox("Hello, my name is " & userinput)

Result:
User enters a C
msg box pops up as "Hello, my name is Tim"

无论我尝试做什么,我都不能让userinput对应于在字符串中解释的变量。如果没有用户的输入引用一个更长,更复杂的短语而对用户来说太难以自行输入,那么我的宏将毫无用处。

3 个答案:

答案 0 :(得分:2)

用户正在输入一个字母。您需要使用代码更明确地将其转换为名称。有很多方法 - 如果您有一个长列表或用户输入的列表,您可能需要一个更动态的解决方案。但是,这是对您的代码的修复:

Dim userinput as String
userinput = inputbox("A=John, B=Kate, C=Tim", "Enter a letter that corresponds with your name: ")
Dim A as String
Dim B as String
Dim C as String
Dim nameOut as String

select case userinput
    case "A"
         nameOut = "John"
    case "B"
         nameOut = "Kate"
    case "C"
         nameOut = "Tim"
end select

Dim Phrase as Variant
phrase = MsgBox("Hello, my name is " & nameOut)

注意:不要忘记用双引号括起字符串。

答案 1 :(得分:1)

发布只是因为它是一种不同的方法。它在三个数组中找到输入字母的位置,然后在名称数组中找到相应的项目。

Sub x()

Dim userinput As String
Dim Phrase As String
Dim v

userinput = InputBox("A=John, B=Kate, C=Tim", "Enter a letter that corresponds with your name: ")
v = Array("John", "Kate", "Tim")

With Application
    If IsNumeric(.Match(userinput, Array("A", "B", "C"), 0)) Then
        Phrase = .Index(v, .Match(userinput, Array("A", "B", "C"), 0))
        MsgBox "Hello, my name is " & Phrase
    Else
        MsgBox "Wrong letter"
    End If
End With

End Sub

答案 2 :(得分:1)

不要忘记Scott的答案,但是对于一种可能更具动态性的方法,似乎class modulescallbyname有答案:

课程模块 - class1

Private pa As String
Public Property Get a() As String
a = pa
End Property
Public Property Let a(value As String)
pa = value
End Property

测试子

Sub testing()
Dim cls1 As Class1
    Set cls1 = New Class1

cls1.a = "tim"

userinput = "a"

Debug.Print CallByName(cls1, userinput, VbGet)

End Sub