test.vbs
vb
1On Error Resume Next '犯人はコイツ
2A = NULL
3If NOT A Is Nothing Then
4 WScript.Echo "NOT NULL"
5End If
6If A Is Nothing Then
7 WScript.Echo "NULL"
8End If
Z:\>cscript test.vbs
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
NOT NULL
NULL
Z:\>
On Error Resume Next をコメントアウトすると
Z:\>cscript test.vbs
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
Z:\test.vbs(3, 1) Microsoft VBScript 実行時エラー: オブジェクトがありません。
Z:\>
ではどうするかというと
test2.vbs
vb
1Option Explicit
2Function IsNullOrNothing(A)
3 IsNullOrNothing = False
4 Select Case VarType(A)
5 Case vbNull
6 IsNullOrNothing = True
7 Case vbObject
8 If A Is Nothing Then
9 IsNullOrNothing = True
10 End If
11 End Select
12End Function
13
14Dim A
15A = Null
16If IsNullOrNothing(A) Then WScript.Echo "Null Or Nothing"
17Set A = Nothing
18If IsNullOrNothing(A) Then WScript.Echo "Null Or Nothing"
Z:\>cscript test2.vbs
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.
Null Or Nothing
Null Or Nothing
vbs を使うコツ
・先頭に Option Explicit を付ける
コーディングミスを防ぐ効用がありますし、変数を確保したかどうかチェックしなくなるのでループ処理等が速くなります。
・On Error Resume Next は局所的に使う
例)
vb
1On Error Resume Next
2' DB 接続処理
3If Err.Number <> 0 Then
4 ' エラー処理
5End If
6On Error Goto 0