You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA中是否存在与SQL ISNULL功能类似的函数?

Replicate SQL's ISNULL Behavior in VBA

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 as Empty), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:37:28