I am getting an overflow error with this code. Please help me understand why. When I comment out the variables j, k, & z I don't get the error. The data is wrong but i don't get the error. What is causing this?
Public Sub CalculateYTDCustomerSalesAndMargins()Dim UniqueCustomers, Output, Claimbacks As VariantDim i, c, j, k, z As DoubleUniqueCustomers = Range("UniqueCustomers")Claimbacks = Range("ClaimBacks")ReDim Output(1 To UBound(UniqueCustomers), 1 To 5)j = 0 'Sales variablek = 0 'Cost of sales variablez = 0 'Claim backs variableFor c = 1 To UBound(UniqueCustomers) For i = 1 To UBound(Claimbacks) If UniqueCustomers(c, 2) = Claimbacks(i, 5) Then j = j + Claimbacks(i, 11) * Claimbacks(i, 10) k = k + Claimbacks(i, 12) * Claimbacks(i, 10) z = z + Claimbacks(i, 22) Output(c, 1) = j Output(c, 2) = k Output(c, 3) = 1 - k / j Output(c, 4) = z Output(c, 5) = 1 - (k - z) / j End If Next ij = 0 'Sales variablek = 0 'Cost of sales variablez = 0 'Claim backs variableNext cRange("E2", Range("I" & UBound(UniqueCustomers) + 1)) = OutputEnd Sub
In line 4, all the variables except z will be Variants, so will take on the type at first usage.
At lines 11 and 12, j and k will become integers, which will cause that error if an attempt is made to set to any value greater than 32767.
Declare each variable with its type
Dim i As Double, c As Double, j As Double, k As Double, z As Double
Mike French
ASKER
Graham,
I tried all this but nothing works. These are all small values that would not exceed 32767 in any case. However even with them set as a "double" data type I still get the error. For whatever reason, it is being caused by lines 27 and 29. I don't know why dividing these numbers is causing this. I have fixed the issue by inserting an "IF" statement that sets Output(c, 3 or 5) to "0" if "k" or "j" are "0". Additionally, "c" reaches 47 before it occurs? Why doesn't it do it before that? I can't see anything in the data that is different before the 47th occurrence?
Sorry I haven't gotten back to you on this. Really busy time of year. anyway, the fix I referred to above is working and I don't have time right now to test your solution. I will test it though as soon as possible.
Thanks for all your help!
GrahamSkan
I couldn't tell whether it applies here, but I should have mentioned that there is a surprising feature (i.e. a bug) whereby an overflow error occurs unexpectedly. This code:
Sub Overflow() Dim a As Double a = 10000 * 10000End Sub
raises an overflow error because the calculation sees the first two operands and assumes that the whole thing deals with integers.
You can get around the problem in several ways:
Sub Overflow() Dim a As Double a =10000# * 10000End SubSub Overflow() Dim a As Double a = CDbl(10000) * 10000End SubSub Overflow() Dim a As Double Dim b As Double b = 1 a = b * 10000 * 10000End Sub
Coul you sen a sample?
Regards