Search code examples
vbaexcel

Using IFERROR in VBA


I hope someone can help me please? I've done a lot of googling and can't figure out what the issue is. I only dabble in vba, so I'm certainly no expert...

I am trying to automate some calculations in a huge spreadsheet at work, and I think I'm probably missing something really silly. Basically, one of the calculations is a simple divide of one cell by another cell. When it hits an error, I want it to return a 0. Here is the code that keeps tripping over:

Sheets("Bridge").Range("W" & SumIfInt) = Application.WorksheetFunction.IfError(Sheets("Bridge").Range("AA" & SumIfInt) / Sheets("Bridge").Range("D" & SumIfInt), 0)

I get a Run-time error 6 Overflow

Thanks in advance


Solution

  • Try this without If error function. As mentioned below, you should use On error resume next very carefully.

    Warning: On error resume next will skip ALL cases of error for rest of the code unless On error goto 0 is present. Also, if you would like to catch a specific error, you can use if error = 'number' then to handle them accordingly. Application.worksheetfunction.iserror is better used in excel, than in excel vba.

        On error resume next
        Sheets("Bridge").Range("W" & SumIfInt) = Sheets("Bridge").Range("AA" & 
        SumIfInt) / Sheets("Bridge").Range("D" & SumIfInt)
    
        if err <>0 then
           Sheets("Bridge").Range("W" & SumIfInt) = 0
        end if
        On error goto 0