Search code examples
vbaexceloffice-2010

Excel VBA Overflows when dividing two Doubles


I'm getting an Overflow error when I try to divide two doubles, and I can't figure out why.

Here's my code as it is now

'x will be used to sum the elements  
Dim x, ct As Double
x = 0
ct = 0
For Each cell In Range(rng)
    If cell.Offset(, offset1).Value = Crit1 And cell.Offset(, offset2).Value = Crit2 Then
        x = x + cell.Value
        ct = ct + 1
    End If
Next

'Divide by count
Avg = x / ct

At first, ct was declared as Long, but I changed it to Double to see if that might fix it, but it didn't.

I've also tried changing the last line to Avg = CDbl(x / ct), but I get the same error.

The values in cell.Value will always be real numbers, usually ranging between 0 and about 9,000,000, occasionally going up as high as 17,000,000. The numbers greater than about 20,000 are almost always integers.


Solution

  • It's divide by zero error. VBA just reported it as "overflow".