Nothingはオブジェクト型
なのでオブジェクト型のみ許容するユーザー定義関数で判定します。
ObjectIsNothing
※Letを使ったシンプルな記述バージョンがコメント欄にあります。
Function ObjectIsNothing(obj As Object) As Boolean
'For Microsoft Office VBA
If obj Is Nothing Then
ObjectIsNothing = True
Else
ObjectIsNothing = False
End If
End Function
厳密に判定するとは
Sub test()
Dim aRs
Set aRs = Nothing
Debug.Print ObjectIsNothing(aRs)
Set aRs = CreateObject("ADODB.Recordset")
Debug.Print ObjectIsNothing(aRs)
End Sub
上記の式で何が起きるかというとエラーが発生します。
aRsは何も型指定していないためVariantになるからです。
もしエラーが起きるのが嫌な場合は obj As Objectを単純にobjにしてください。
するとvariantはエラーではなく、型が違うためFalseが返るようになります。
エラーが起きるのが嫌な場合は以下のIsNothingのほうがいいです。
Sub test()
Dim aRs As Object 'Objectと明確に宣言する
Set aRs = Nothing
Debug.Print ObjectIsNothing(aRs) 'NothingなのでTrueになる
Set aRs = CreateObject("ADODB.Recordset")
Debug.Print ObjectIsNothing(aRs)
End Sub
ObjectIsNothig関数で
実際は厳密に比較しないIsNothingが便利かも
IsNothing関数
※Letを使ったシンプルな記述バージョンがコメント欄にあります。
Function IsNothing(varVari) As Boolean
'For Microsoft Office VBA
If varVari Is Nothing Then
IsNothing = True
Else
IsNothing = False
End If
End Function
実際はVariantでもObjectでもNothingかどうかを判定するほうがあっているので、そういうIsNothing関数を作ってみました。
変数varVariはVariant型のため、Object、VariantどちらでもNothingか判定します。