首页 > 解决方案 > 单元格值不正确

问题描述

试图让X5价值根据L5价值改变。620无论价值如何,代码都只会返回L5,有人可以告诉我我做错了什么。

'Change Peak Flow For Age Group

    Dim score As Integer, result As String
        score = Range("L5").Value

    If score => 35 < 40 Then
        Range("X5").Value = "620"
        Else
    If score => 40 < 45 Then
        Range("X5").Value = "610"
        Else
    If score => 45 < 50 Then
        Range("X5").Value = "600"
        Else
    If score => 50 < 55 Then
        Range("X5").Value = "580"
        Else
    If score => 55 < 60 Then
        Range("X5").Value = "560"
        Else
    If score => 60 < 65 Then
        Range("X5").Value = "550"
        Else
    If score => 65 < 70 Then
        Range("X5").Value = "525"
        Else
    If score => 70 < 75 Then
        Range("X5").Value = "490"
        Else
    If score => 75 < 79 Then
        Range("X5").Value = "450"
        Else
    If score => 80 < 85 Then
        Range("X5").Value = "430"

    End If
    End If
    End If
    End If
    End If
    End If
    End If
    End If
    End If
    End If

    End Sub

标签: excelvba

解决方案


  1. 语法错误,您的If score => 35 < 40 Then逻辑有缺陷。If score => 35 < 40 Then解析为“如果分数大于或等于 True 则”
  2. 你的理论逻辑是多余的。如果分数不小于 55,则没有理由在此之后检查它是否大于或等于 55。
  3. 选择案例在这里可能更合适。
  4. 当应该使用实数时,不要使用看起来像数字的文本。
  5. 没有规定分数低于 35 或高于 85 的情况

更正:

if score >= 35 and score < 85 then
    If score < 40 Then
        Range("X5").Value = 620
    ElseIf score < 45 Then
        Range("X5").Value = 610
    ElseIf score < 50 Then
        Range("X5").Value = 600
    ElseIf score < 55 Then
        Range("X5").Value = 580
    ElseIf score < 60 Then
        Range("X5").Value = 560
    ElseIf score < 65 Then
        Range("X5").Value = 550
    ElseIf score < 70 Then
        Range("X5").Value = 525
    ElseIf score < 75 Then
        Range("X5").Value = 490
    ElseIf score < 79 Then
        Range("X5").Value = 450
    ElseIf score < 85 Then
        Range("X5").Value = 430
        ...
    End If
else
    Range("X5").clearcontents
end if

改写:

if score >= 35 and score < 85 then
    select case true
        case score < 40
            Range("X5").Value = 620
        case score < 45
            Range("X5").Value = 610
        case score < 50
            Range("X5").Value = 600
        case score < 55
            Range("X5").Value = 580
        case score < 60
            Range("X5").Value = 560
        case score < 65
            Range("X5").Value = 550
        case score < 70
            Range("X5").Value = 525
        case score < 75
            Range("X5").Value = 490
        case score < 79
            Range("X5").Value = 450
        case score < 85
            Range("X5").Value = 430
    end select    
else
    Range("X5").clearcontents
end if

推荐阅读