Write #REF! in cell

User avatar
ErikJan
BronzeLounger
Posts: 1254
Joined: 03 Feb 2010, 19:59
Location: Terneuzen, the Netherlands

Write #REF! in cell

Post by ErikJan »

I want to write #REF! in a cell using VBA (to indicate an error in a VBA function); how do I do that?

User avatar
HansV
Administrator
Posts: 78545
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Write #REF! in cell

Post by HansV »

Like this:

Range("A1") = CVErr(xlErrRef)

Other possible error values:

xlErrDiv0: #DIV/0!
xlErrNA: #N/A
xlErrName: #NAME?
xlErrNull: #NULL!
xlErrNum: #NUM!
xlErrValue: #VALUE!
Best wishes,
Hans

User avatar
ErikJan
BronzeLounger
Posts: 1254
Joined: 03 Feb 2010, 19:59
Location: Terneuzen, the Netherlands

Re: Write #REF! in cell

Post by ErikJan »

It's the return value of a user function, I don't know which cell... WIll try CVErr(xlErrRef)... Was thinking about "Error(a number)" or something like that

Update - it works!

User avatar
HansV
Administrator
Posts: 78545
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Write #REF! in cell

Post by HansV »

User-defined functions will automatically return an error value in the cell if they fail. If you want to return an error value in specific circumstances, you can use code like this:

Code: Select all

Function MyFunction()
    ...
    If <some condition> Then
        MyFunction = CVErr(xlErrNum)
        Exit Function
    End If
    ...
End Function
If you want to replace the built-in error value with a user-defined return value, use an error handler:

Code: Select all

Function MyFunction(x As Long, y As Long)
    On Error GoTo ErrHandler
    MyFunction = y / x
    Exit Function
ErrHandler:
    MyFunction = "!@#$%^&*"
End Function
Best wishes,
Hans