1

I have some vba behaviour that I do not understand. I'm running vba in a macro of excel 2016.

Sub alpha()

Dim a As Integer, b As Long
a = 750
b = 50 * a

Stop

End Sub

Running this sub results in an overflow error. Why?

Variable a is an integer and therefore cannot hold the number 750*50 because that is too high. But variable b is dimensionalised as a long - so it should be able to hold that number.

Strangely - If I change the type of variable a to Long then the code runs through.

5
  • 2
    the language does not know (yet) that the result will end up in b, all it has is the "50" so it chooses an integer to begin with. Commented Apr 26, 2018 at 8:45
  • change Dim a As Integer to Dim a As Long Commented Apr 26, 2018 at 8:47
  • 2
    Or b = 50 * cLng(a): VBA is not doing an implicit conversion from Integer to Long until after it has done the calculation. Commented Apr 26, 2018 at 8:49
  • 1
    And read why you can always use Long instead of Integer in VBA because there is no benefit in using Integer at all. Commented Apr 26, 2018 at 8:50
  • Possible duplicate of Overflow when multiplying Integers and assigning to Long Commented Apr 26, 2018 at 8:58

1 Answer 1

2

The maximum value for an Integer in VBA is 32,767.

You are overflowing that with 50 * a. It's not relevant that you want to assign that to a Long as conceptually the multiplication happens prior to the assignment, and by then, the damage has been done.

Use a Long instead for a or write

b = 50& * a

to force type promotion. Either are good up to 2,147,483,647

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.