从单元格检索比较运算符

时间:2018-10-23 09:40:50

标签: excel vba excel-vba

我正在尝试为excel创建vba代码,在这里我可以从excel工作表中检索比较运算符(例如<,<=等)。我正在尝试根据值和输入的范围给出分数。

我想在代码中执行以下操作:

样本数据:

cell A1 = 80(input)
cell A4 = "<"
cell B4 = 75
cell C4 = "="
cell D4 = 75
cell E4 = ">"
cell F4 = 75

我想做的代码示例:

dim score as integer
dim result as integer 
score = range("A1").value

methodoperatorb1 = range("A4").value
methodoperatorb2 = range("C4").value
methodoperatorb3 = range("E4").value

band1 = range("B4").value
band2 = range("D4").value
band3 = range("F4").value

if score (methodoperator1)(band1) then result = 1
elseif score (methodoperator2)(band2) then result = 2
else result = 3

不好意思,我很希望有人能帮助我解决这个问题。

1 个答案:

答案 0 :(得分:2)

您可以使用Evaluate来评估这样的表达式:

Sub foo()

    Dim score As Integer
    score = Range("A1").Value

    methodoperatorb1 = Range("A4").Value
    methodoperatorb2 = Range("C4").Value
    methodoperatorb3 = Range("E4").Value

    band1 = Range("B4").Value
    band2 = Range("D4").Value
    band3 = Range("F4").Value

    Dim result As Integer
    If Application.Evaluate(score & methodoperatorb1 & band1) Then
        result = 1
    ElseIf Application.Evaluate(score & methodoperatorb2 & band2) Then
        result = 2
    Else
        result = 3
    End If
    MsgBox result
End Sub

请注意,这仅在表达式的总长度小于256个字符时才有效。