VBA中是否存在与SQL ISNULL功能类似的函数?
Great question! VBA doesn't have a native function that matches SQL's ISNULL exactly, but we can easily build one (or use existing workarounds) to get the behavior you need: return the second parameter if the first is empty/null, otherwise return the first parameter.
Custom ISNULL Function (Most Like SQL)
The cleanest way to mirror SQL's ISNULL is to create a custom VBA function. This lets you call it exactly like you would in SQL, e.g., ISNULL(A1, B1) directly in your worksheet.
Here's the code:
Function ISNULL(val1 As Variant, val2 As Variant) As Variant ' Returns val2 if val1 is Null or empty (Excel blank cell), else returns val1 If IsNull(val1) Or val1 = Empty Then ISNULL = val2 Else ISNULL = val1 End If End Function
How it works with your examples:
- Case 1:
ISNULL(A1, B1)→ A1 is a blank cell (which VBA treats asEmpty), so the function returns B1's value: Apple - Case 2:
ISNULL(B1, C1)→ B1 has a value (Apple), so the function returns B1 directly: Apple
Workarounds Without Custom Functions
If you don't want to add a custom function, you can use inline logic in VBA or Excel worksheet formulas:
In VBA Code
Use IIf combined with checks for both Null and Empty:
Dim targetResult As Variant targetResult = IIf(IsNull(Range("A1").Value) Or Range("A1").Value = Empty, Range("B1").Value, Range("A1").Value)
In Excel Worksheet Formulas
For direct cell use, combine IF with checks for blank states:
- For strictly blank cells:
=IF(ISBLANK(A1), B1, A1) - For blank cells or cells with empty strings (
""):=IF(OR(ISBLANK(A1), A1=""), B1, A1)
Important Note
Remember: VBA's native IsNull function only detects actual Null values, not Excel's blank cells (which are Empty). That's why our custom function includes both checks—so it handles both scenarios correctly.
内容的提问来源于stack exchange,提问作者Thompson Ho

