Excel VBA 范围值有时无法通过比较检查

Excel VBA range value sometimes fails a comparison check

情况

在工作表上我有一个名为 total_Distnamed range(这是一个介于 0 和 1 之间的值,格式为百分比)。

VBA 中,我正在使用 IF 语句检查此值是否 =1。这是完整的代码,我通过注释 ****Issue occurs here*** 突出显示了 IF 语句。用户按下工作表上的按钮调用该代码。

Sub distribution_Next()

    Dim tbl As ListObject
    Dim i As Integer

    Set tbl = Range("tbl_Activity").ListObject

    '****Issue occurs here***
    If Range("total_Dist").Value <> 1 Then   'the time allocation does not equal 100%
        MsgBox "Please ensure the total time allocated adds up to 100%"
        GoTo clean
    Else
        Debug.Print "else"
    End If

    Application.ScreenUpdating = False

    With tbl
        For i = 1 To .ListColumns(2).DataBodyRange.Rows.Count
            'enable/visible each worksheet that has a time allocation
            If .ListColumns(2).DataBodyRange.Cells(i, 1).Value > 0 Then
                Worksheets(.ListColumns(1).DataBodyRange.Cells(i, 1).Value).Visible = True
            Else
                Worksheets(.ListColumns(1).DataBodyRange.Cells(i, 1).Value).Visible = False
            End If
        Next i
    End With

    Sheets("Finish").Visible = True
    Worksheets("Distribution of Time").Activate     'included this line to stop 'nextPage' going to incorrect sheet

    Application.ScreenUpdating = True

    nextPage

clean:
    'clean up
    Set tbl = Nothing

End Sub

问题

有时候,即使在range = 1时,代码仍然进入IF语句,如截图所示:

从tiptext可以看出,'Watches'window的值是=1,但是还是进入了IF语句

这不是每次都会发生,但我看不出规律或弄清楚为什么它会像这样失败。

备注

我试过不带 .value,带 .value2

我在 Windows 7 机器上使用 Excel 2013。

编辑/更新

此屏幕截图显示它有时会通过 IF 检查:

我认为这是一个浮点数问题,所以实际值不精确为 1。如果是这样,您可以使用:

If Round(Range("total_Dist").Value, 7) <> 1 Then

例如。 7 是一个任意数字,具体取决于您需要的精度级别。我倾向于使用它,因为它通常有足够的小数位来排除浮点错误,但不会引入新的舍入问题。 (请记住,对于显示为 2DP 的百分比值,将实际值四舍五入为 4 DP 可能会影响基于实际值而不是浮点问题的结果。)