0

I am writting a CRC8 function in VBA which results in error: Overflow !

Since I cannot fix it and there are no sample code solutions on how to fix the overflow error with left shifting, I`d like to try and turn it off to see the result I get.

I cannot find it in options.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
David Kasabji
  • 1,049
  • 3
  • 15
  • 32

3 Answers3

4

I cannot find it in options.

This is because it is a runtime error, not an "option."

Most likely a cause of an Overflow error is trying to slick a number that's too huge for the data type.

Byte type is for 0-255. Integer type can hold numbers up to 32,767. Long data type can hold numbers up to 2,147,483,647 so it's probably better suitable for your specific case.

Adjust your variables types accordingly.

Generally, VBA converts all Integers to Long these days so it's a better practice to dim your variables as Long by default.


Here is an excellent writup as to why you should use them as Long.

Community
  • 1
  • 1
enderland
  • 13,825
  • 17
  • 98
  • 152
3

Here is how you left shift a Byte without overflowing:

Dim abyte as Byte
abyte = &H81 '10000001

'To shift left, you multiply by 2, BUT because the msb is 1, multiplying by 2 gives you an Overflow.
'To fix that, you first mask off the leftmost bit, THEN multiply by 2...

'abyte is                              10000001
'And it with the mask &H7F         And 01111111
'which results in                    = 00000001
'multiplied by 2 is               *2 = 00000010

abyte = (&H7F And abyte) * 2
Blackhawk
  • 5,984
  • 4
  • 27
  • 56
-4

Use:

On Error Resume Next ' Disable Error Handler
  .. do the calculation ..
  If Err Then 
     ' Handle Error
  End If
On Error Goto 0   ' Activate Error Handler
Klaus
  • 903
  • 8
  • 19