Word VBA OverFlow Error When Multiplying/Adding Integers

It might have occurred to you when working with integers in VBA for Word that you get  the following error:

Overflow error

This error generally occurs when  you are doing arithmetic operations on integer values that result in:

  1. Values larger than 32767
  2. Values smaller than -32768

This is because integers only accept values in the range [-32768, 32767]. Numbers larger than 32767 or smaller than -32768 must be stored in a Long variable. In some office applications this conversion is done implicitly (i.e VBA for Excel). In VBA for word the conversion must be done explicitly.

All the following codes will result in an error:

Dim intValue As Integer
intValue = -500 * 500

Dim intValue As Integer
intValue = 32767 + 1

Dim intValue As Integer
intValue = 32768

Dim i As Integer
For i = 1 To 32766
...
Next

Solution:

Dim lngValue As Long
lngValue = -CLng(500) * CLng(500)

Dim lngValue As Long
lngValue = CLng(32767) + CLng(1)

Dim lngValue As Long
lngValue = 32768 

Dim i As Long
For i = 1 To 32766
...
Next i

 

 

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

4 thoughts on “Word VBA OverFlow Error When Multiplying/Adding Integers”

  1. ywwp says:

    But integer data type variable works fine and does not show overflow error for negative values. any reason?

    1. pedrumj says:

      Hi

      Good point. I should have mentioned negative integer values can go up to -32768. You will get an overflow error with the code below:

      Sub test()
      Dim intValue As Integer
      intValue = -32769
      End Sub

      I will add this to my post. Thanks 🙂

      1. ywwp says:

        oh, i hv not gone on negative side beyond 3000. never required. thanks on this info, and appreciated your support. regards

        1. pedrumj says:

          No problem, Glad you found this post useful.

Leave a Reply

Your email address will not be published. Required fields are marked *