Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

excel - Why is 0 divided by 0 throwing an overflow error in VBA?

Why is 0/0 throwing Overflow error in VBA, while in .Net languages it is simply a Division by 0 error?


E.g., in C# it is a System.DivideByZeroException

static void Main()
{
    int k = 0;
    int p = 0;
    Console.WriteLine(k/p);
}

Div/0 error exists in VBA. But 0/0 gives an overflow exception, while anything else divided by 0 gives a Div/0 exception:

Public Sub TestMe()

    'Integer
    PrintAndCheck (11)      '- Division by zero error

    'Double
    PrintAndCheck (0.9)     '- Division by zero error

    'Long
    PrintAndCheck (50000)   '- Division by zero error

    'String
    PrintAndCheck ("1.1")   '- Division by zero error

    '----------------------------------------------------
    '----------------BUT---------------------------------
    '----------------------------------------------------

    'Integer
    PrintAndCheck (0)       '- Overflow?

End Sub

Public Sub PrintAndCheck(lngDivisor As Variant)

    On Error Resume Next

    Debug.Print lngDivisor / 0
    Debug.Print Err.Description & " from type -> " & VarType(lngDivisor)

    On Error GoTo 0

End Sub

That's what you get in the immediate window:

Division by zero from type -> 2
Division by zero from type -> 5
Division by zero from type -> 3
Division by zero from type -> 8
Overflow from type -> 2

Edit: To make the whole story more interesting:

Public Sub TestMe()
    On Error Resume Next
    Debug.Print Evaluate("0/0")     'Division by 0 error (CVErr(xlErrDiv0)=2007)
    Debug.Print 0  0               'Division by 0 error
    Debug.Print Err.Description
    On Error GoTo 0
End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/floating-point-division-operator

Besides the obvious differences in implementation of languages and the way VBA handles division, MS Doc link above expands on the reasons for overflow exception , that if the operand data types are integer then it will throw Overflow exception (Last statement below)

enter image description here

Alternatively there is division operator that checks the range for you and throws Division by zero exception


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...