Home » excel » excel – Define a custom VBA function that returns blank

excel – Define a custom VBA function that returns blank

Posted by: admin May 14, 2020 Leave a comment

Questions:

How do I define an excel function that returns a blank if the result of the formula is blank?

If vlookup finds a blank, it returns a zero. I’d like to embed vlookup in a function that, if vlookup finds a blank cell, returns a blank instead of a zero.

I don’t want to have to type out:

=if(vlookup(args) = "", "", vlookup(args))

I would prefer to have something similar to the built in Iferror function whose syntax would be:

=blankreturn(function)

Which would return a blank if the function results in a blank, or the result of the function if it does not.

I have tried to define a custom function but it still returns a zero when it finds a blank cell

public Function Blankreturn(formula as variant)

If IsEmpty(formula) = True Then
   Blankreturn = ""
Else
   Blankreturn = formula
End if

End Function

Or even better, though I wouldn’t know where to start with the code for this:

ifblank(function, "This is blank")

Which, if the first argument results in a blank, returns the second argument.

Thanks

How to&Answers:

You could build your special VLookup function

Option Explicit

Public Function MyVLookup(Arg1, Arg2, Arg3, Optional Arg4 = True)
    MyVLookup = Application.VLookup(Arg1, Arg2, Arg3, Arg4)
    If VarType(MyVLookup) = 0 Then MyVLookup = vbNullString
End Function

enter image description here

But possibly using a VBA user definde function is slower than using this method =if(vlookup(args) = "", "", vlookup(args)) I could imagine (would need to be tested).