简体   繁体   English

使用Double的错误处理不起作用-VBA Excel

[英]Error handling using double not working - VBA excel

I have a simple error checking problem. 我有一个简单的错误检查问题。 At the start of my sub I'm making sure that a range adds up to 100%. 在开始我的练习时,我要确保范围的总和为100%。 I do this by getting the value of a Cell "F3" using Range.value and storing it as a double. 我通过使用Range.value获取单元格“ F3”的值并将其存储为双精度值来实现。 F3 contains a SUM formula that checks another range. F3包含一个SUM公式,用于检查另一个范围。

I can see that in the locals window the value of the double is 1 (because the values add up to 100%), however, the code still gets into the If statement below and exits the sub. 我可以看到在locals窗口中double的值是1(因为这些值的总和为100%),但是,代码仍然进入下面的If语句并退出子程序。

Sub dataCollection()

'Define sheets
Dim ipt As Worksheet
Set ipt = Sheets("Input form")

'Check that allocation is 100%
Dim alloc As Double
alloc = ipt.Range("F3").Value

If alloc <> 1 Then
    MsgBox "Error, allocation does not equal 100%"
    Exit Sub
End If

...

End Sub

Is this a problem with using a double in this way or something? 以这种方式使用double是否有问题?

Using double or any floating point number in computer languages is a well known problem. 在计算机语言中使用double或任何浮点数是一个众所周知的问题。 Thus, you should never compare double values. 因此,永远不要比较双精度值。 Or you should be careful, when doing so. 否则,您应该小心。 In your case, use something like: 在您的情况下,请使用以下方法:

If Abs(alloc-1) > 0.000000001 Then

More reading here: Floating point inaccuracy examples 此处更多阅读内容: 浮点误差示例

In general, to understand what is happening, try the following code in a new excel workbook: 通常,要了解发生了什么,请在新的excel工作簿中尝试以下代码:

Option Explicit

Public Sub TestMe()

    Dim cntSum      As Double

    Cells.Clear

    Cells(1, 1) = 0.3
    Cells(2, 1) = 0.2
    Cells(3, 1) = 0.2
    Cells(4, 1) = 0.2
    Cells(5, 1) = 0.1

    cntSum = Cells(1, 1) + Cells(2, 1) + Cells(3, 1) + Cells(4, 1) + Cells(5, 1)

    Debug.Print cntSum
    Debug.Print cntSum = 1
    Debug.Print cntSum - 1

End Sub

You will have the following in the console: 控制台中将具有以下内容:

 1 
False
-1,11022302462516E-16 

It will mean that cntSum is 1 (first line), but it is not equal to 1 (second line) and the absolute difference between it and 1 is -1,11~E-16 . 这将意味着cntSum1 (第一行),但不等于1(第二行),并且它与1之间的绝对差为-1,11~E-16

In Excel, a way to go around this is using the Currency format. 在Excel中,一种解决方法是使用“ Currency格式。 Add this line: 添加此行:

Range("A1:A5").Style = "Currency"

after the Cells.Clear code and run it again. Cells.Clear代码之后,然后再次运行。 Now the result is different. 现在结果不同了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM