View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default How to use IfError in Excel 2007 VBA ?

When VBA tries to evaluate the div/0 an error is raised before getting to
the IFError worksheet function. Here's a couple of examples

Sub test()
Dim s As String
Dim x As Double, v

s = "=" & ActiveSheet.Cells(1, 1).Address & "/" & ActiveSheet.Cells(1,
2).Address
ActiveSheet.Cells(1, 3).Formula = s
x = WorksheetFunction.IfError(ActiveSheet.Cells(1, 3), 99)
ActiveSheet.Cells(1, 4) = x

v = CVErr(xlErrDiv0)
x = WorksheetFunction.IfError(v, 123)
ActiveSheet.Cells(1, 5) = x

End Sub

Wouldn't normally use the IFError function in VBA
On error resume next
v = 1/0
if err.number = 9 then
' code
elseif etc
End if
On error goto 0

Regards,
Peter T

"Xavier" wrote in message
...
The division by zero that I mention is just a way for me to quickly test
the IfError function. I need to use it in a different context to trap
other errors. This is the simplest example I have been able to produce but
still can't get it to work. :-(


"Dave Peterson" wrote in message
...
It would make more sense to me to just check the denominator cell for 0.

dim myVal as double
myVal = 99
With activesheet
if application.isnumber(.cells(1,1).value) then
if application.isnumber(.cells(1,2).value) then
if .cells(1,2).value < 0 then
myval = .cells(1,1).value / .cells(1,2).value
end if
end if
end if
.cells(1,3).value = myval
end with




Xavier wrote:

Hello,

I am trying to figure out how to use the IfError function with Excel
2007
VBA. I have built a simple spreadsheet to test division by zero error
handling. The following line either performs the division or throws an
error
11 (division by 0) instead of returning 99.

ActiveSheet.Cells(1, 3) =
WorksheetFunction.IfError((ActiveSheet.Cells(1, 1)
/ ActiveSheet.Cells(1, 2)), 99)

Any help would be appreciated.

Thanks,

Xavier


--

Dave Peterson