选择Case错误输出

时间:2016-05-16 17:18:20

标签: excel vba select case

所以我试图让我的宏在一张表中为我分析一些数据。数据位于单元格B2到B6上,是0到4(小数点)之间的数字。

我无法弄清楚我在使用代码时遇到了什么问题,它在不同单元格上的不同条件下工作得很好,如下所示

此代码有效:

Sub Salmondepthoutlet()
    Dim score As Double, result As String
Dim Rng As Range, i As Long

i = 0

With Sheets("Vertical")
    For Each Rng In .Range("B7:B16")
        score = Rng.Value
        Select Case score
            Case Is >= 0.15
                result = "1"
            Case 0.11 To 0.14
                result = "0.6"
            Case 0.08 To 0.1
                result = "0.3"
            Case Is <= 0.07
                result = "0"
        End Select
        .Range("B26").Offset(i).Value = result
        i = i + 1
    Next Rng
End With
End Sub

但是这段代码没有(B21中没有任何内容出现输出&amp;结果对其他人来说是错误的)

Sub Salmonvelocityoutlet()
Dim score As Double, result As String
Dim Rng As Range, i As Long

i = 0

With Sheets("Vertical")
    For Each Rng In .Range("B2:B6")
        score = Rng.Value
        Select Case score
            Case Is >= 3
                result = "0"
            Case 2.99 To 2.6
                result = "0.3"
            Case 2.59 To 2.09
                result = "0.6"
            Case Is <= 2
                result = "1"
        End Select
        .Range("B21").Offset(i).Value = result
        i = i + 1
    Next Rng
End With
End Sub

提前感谢您的帮助&amp;时间

1 个答案:

答案 0 :(得分:1)

我怀疑你遇到了结果问题&#34;在边缘&#34; (基本上是舍入错误),因为Excel使用IEEE标准进行双精度数学运算,并且您使用的是十进制值。根据您所写的内容,某些值甚至可能永远不会出现。除非您想明确排除0到3范围内的某些值,否则我建议您将select语句重写为:

Select Case score
        Case Is >= 3
            result = "0"
        Case Is >= 2.6
            result = "0.3"
        Case Is > 2
            result = "0.6"
        Case Is > 0  'Or Case Else
            result = "1"
    End Select