简体   繁体   中英

Excel VBA throws overflow error with a simple division

Excel 2013. VBA: This code:

Sub test()
On Error GoTo Err:
Dim p As Double

p = (362 * 100) / 2005
Exit Sub
Err:
    If Err.Description <> "" And Err.Source <> "" Then
        MsgBox Err.Description, vbCritical, Err.Source
    End If
End Sub

Throws Overflow number 6 error. Why?

The error is on 362 * 100 . It is considered Integer and it is up to 32767 .

Try like this:

Public Sub TestMe()    
    Dim pct As Double
    pct = (CDbl(362) * 100) / 2005        
End Sub

The problem is that if you have any of the following 4 mathematic expressions ( +-/* ) with values under 2^15-1 or 32767 , VBA considers them Integer and the result is tried to be parsed to Integer as well. (The Integer values are actually from -32768 to 32767 )

Thus, 32767+1 gives an overthrow error. If you try with 32768+1 it will be ok, because 32768 will be parsed to Long .

For the power operator, ^ , VBA parses to Double and it is quite ok - 2 ^ 10 + 32000

因为VBA中的Integer类型是16位带符号的,并且36200溢出了其最大值32767。您可以通过将&附加到操作数之一以使其为Long字面量来避免这种情况,例如(362& * 100) / 2005

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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