Excel VBA范围值有时无法进行比较检查
情况
在工作表上,我有一个named range
total_Dist
的named range
(这将是一个0和1之间的值,格式为百分比)。
在VBA
我使用IF
语句来检查这个值是否=1
。 这里是整个代码,并且我已经通过注释****Issue occurs here***
突出显示了IF
语句****Issue occurs here***
。 该代码由用户在工作表上按下button调用。
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'窗口看到值=1
,但它仍然进入了IF
语句。
这不会每次都发生,但是我看不到一个模式,或者弄清楚为什么会这样失败。
笔记
我已经尝试没有.value
和.value2
。
我在Windows 7机器上使用Excel 2013。
编辑/更新
这个截图显示了它有时会通过IF
检查:
我会想象这是一个浮点问题,所以实际的价值不是精确1.如果是这样你可以使用:
If Round(Range("total_Dist").Value, 7) <> 1 Then
例如。 7是一个任意数字,取决于你所需要的精度水平。 我倾向于使用它,因为它通常是足够的小数位来排除浮点错误,但不会引入新的舍入问题。 (请记住,对于显示为2DP的百分比值,将实际值四舍五入可能会影响基于实际值的结果,而不是浮点问题。)