Overflow error 6

ADOUser
01-25-2006, 07:28 AM
In my VB project I have a progress bar which I increment to display the progress of the process when the program runs. I get an overflow error at the code where I increment the progressbar.value. Here is the code.

Dim nTotal As Integer 'Items in queue
Dim nCount As Integer 'Items processed so far

'********************************************************
'** Update the progress bar
'********************************************************* If nCount > nTotal Then
Let prgProgress.Value = 100
Else
Let prgProgress.Value = (nCount * 100) / nTotal
End If

nTotal was 392 and the nCount was 328 when this error happend. Can anyone help me with this problem???

George7a
01-25-2006, 07:48 AM
Hi,

Because "(nCount * 100)" will get over flow .. it is too big for an integer.

If you dim as long it will solve..

- George

ADOUser
01-25-2006, 10:26 AM
Hi,

Because "(nCount * 100)" will get over flow .. it is too big for an integer.

If you dim as long it will solve..

- George


I dont see it that way. Because I have defined nCount as Integer and not the product ("nCount * 100) as Integer. I can define nCount and nTotal as Long, incase those numbers get bigger than the integer range. What I found in Microsoft website is convert the 100 to Long. So the final equestion will look like this
prgProgress.value = (nCount * CLng(100))/nTotal
Since I cant reproduce the error and it happens in client machine, I wouldnt know for sometime if this change worked.
Thank you

Deadalus
01-25-2006, 12:44 PM
Both solutions will work. In a mathematical operation with two Integers, VB assumes that the result will also be an Integer. In other words, the temporary variable used for storing the result of nCount * 100 will be of type Integer, and that's the one that will overflow when the product is bigger than the max value for Integers.

To clearly see this, try:
Debug.Print 100 * 1000
No explicit variables involved, and yet there will be an overflow.

If a Long is involved in an operation, VB assumes that the result will be a Long too. That's why both declaring nCount as Long and explicitly saying that 100 should be treated as a Long avoid the error.

Note that you can also use & to treat a literal as a Long:
Debug.Print 100& * 1000

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum