在 Excel VBA 中,“IsNull()”和“var = Null”之间有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12750839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:00:29  来源:igfitidea点击:

In Excel VBA, what are the differences between "IsNull()" and "var = Null"?

excel-vbanullruntime-errorstringvba

提问by XenoRo

Consider the following VBA function:

考虑以下 VBA 函数:

Function getFirstColumn(Optional sheetName As String) As Long
    'In particular the IF statement below.
    If sheetName = "" Or sheetName = Null Then sheetName = ActiveWorkbook.ActiveSheet.Name
    With ActiveWorkbook.Worksheets(sheetName)
        getFirstColumn = .Cells.Find("*", .Cells(1), xlFormulas, xlWhole, xlByColumns, xlNext).Column
        If Err <> 0 Then getFirstColumn = 0
    End With
End Function

When using this function, I don't have problems when using it from a second opened sheet.

使用此功能时,从第二个打开的工作表中使用它时没有问题。

But when the code is changed to it's function-based equivalent, 'If IsEmpty(sheetName) Or IsNull(sheetName) Then sheetName = ActiveWorkbook.ActiveSheet.Name, I get problems if I try to use the function from a sheet that doesn't own it:

但是,当代码更改为基于函数的等效代码时'If IsEmpty(sheetName) Or IsNull(sheetName) Then sheetName = ActiveWorkbook.ActiveSheet.Name,如果我尝试从不拥有它的工作表中使用该函数,则会出现问题:

Erro em tempo de execu??o '9':
Subscrito fora do intervalo.

Erro em tempo de execu??o '9':
Subscrito fora do intervalo。

What are the differences between them? And why is such error triggered exactly?

它们之间有什么区别?为什么会准确触发此类错误?

回答by paulsm4

"sheetName" is a variable. The variable may be undefined, might refer to an object ... or might be NULL.

“sheetName”是一个变量。变量可能是未定义的,可能是指一个对象......或者可能是 NULL。

If it's an object, the object itself might evaluate to the variant value NULL. Hence the "IsNull()" function.

如果它是一个对象,则该对象本身可能会评估为变体值 NULL。因此,“IsNull()”函数。

Other variants include "IsEmpty()" (which you mentioned), "IsNothing()" and even "IsMissing()":

其他变体包括“IsEmpty()”(您提到的)、“IsNothing()”甚至“IsMissing()”:

回答by Wolfgang Kuehn

In VBA, an unspecified, optional string evaluates to an empty string.

在 VBA 中,未指定的可选字符串计算为空字符串。

Therefore sheetName is the empty string if getFirstColumn is called with no argument, and

因此,如果不带参数调用 getFirstColumn,那么 sheetName 是空字符串,并且

sheetName = "" is true
isEmpty(sheetName) is false
isNull(sheetName) is false
sheetName = Null is Null btw.

So go for the first option.

所以选择第一个选项。