View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
MichaelDavid MichaelDavid is offline
external usenet poster
 
Posts: 100
Default Overflow Error But Right Answer is Produced

Greetings! The below code generates an overflow error when aNumShrs(21, 1)
contains 15749.9999602351, and the macro executes the line which reads:
TotalSharesPurchased = TotalSharesPurchased + aNumShrs(lRow, 1)

Dim aNumShrs As Variant
Dim aPrice As Variant
Dim TotalPurchases As Double
Dim TotalSharesPurchased As Long

If aPrice(lRow, 1) - MaxPrice 0# Then MaxPrice = aPrice(lRow, 1)
TotalPurchases = TotalPurchases + aPrice(lRow, 1) * aNumShrs(lRow, 1)
TotalSharesPurchased = TotalSharesPurchased + aNumShrs(lRow, 1)

When I modified the above code as follows:

Dim aNumShrs As Variant
Dim aPrice As Variant
Dim TotalPurchases As Double
Dim TotalSharesPurchased As Long
Dim NumShares As Double
Dim NumSharesLong As Long

NumShares = Round(aNumShrs(lRow, 1), 2)
NumSharesLong = NumShares
If aPrice(lRow, 1) - MaxPrice 0# Then MaxPrice = aPrice(lRow, 1)
TotalPurchases = TotalPurchases + aPrice(lRow, 1) * aNumShrs(lRow, 1)
TotalSharesPurchased = TotalSharesPurchased + NumSharesLong

I still get the overflow error, but I can tell by holding my cursor over the
variables in the above, that the right answer is being generated. But the
overflow error prohibits the program from continuing. So I then added On
Error Resume Next to the above logic as follows:

On Error Resume Next
NumShares = Round(aNumShrs(lRow, 1), 2)
NumSharesLong = NumShares
On Error GoTo 0
If aPrice(lRow, 1) - MaxPrice 0# Then MaxPrice = aPrice(lRow, 1)
TotalPurchases = TotalPurchases + aPrice(lRow, 1) * aNumShrs(lRow, 1)
TotalSharesPurchased = TotalSharesPurchased + NumSharesLong

Now the logic runs without a hitch and produces the right answer, and the
macro containing the above logic runs to completion. Is there any way to code
this without using On Error Resume Next?

--
May you have a most blessed day!

Sincerely,

Michael Fitzpatrick