0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VBA Object型の変数がNothingであるか厳密に判定するObjectIsNothing関数と異型許容NothingであるIsNothing関数

Last updated at Posted at 2019-11-10

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か判定します。

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?