A strange error VBS empty variable judgment

Today, I put a VBA function written by myself into VBS to run, and found an unexpected weird error: empty variable judgment error!

The code is simplified as follows:

Option Explicit
dim DB

If DB Is Nothing Then
		'--------------------------
		Set DB = CreateObject("ADODB.Connection")  '数据库引擎'New ADODB.Connection
		'-----------------
end if

Set DB = Nothing

The original intention is to judge whether the DB object has been initialized, but an error is reported here in Is Nothing. After checking, it is found that if it is judged by Is Nothing, it needs to be initialized as an object, and there was no error in VBA before because the variable was defined first: Public DB As Connection, it can be seen that it is necessary to develop a good habit of variable initialization.

After the above code initializes the variables, it can run normally:

Option Explicit
dim DB

Set DB = Nothing	' 必须初始化为 Nothing 才能用 is Nothing 判断。否则报错。

If DB Is Nothing Then
		'--------------------------
		Set DB = CreateObject("ADODB.Connection")  '数据库引擎'New ADODB.Connection
		'-----------------
end if

If DB Is Nothing Then
	msgbox "db Nothing"
else
	msgbox "db OK"
end if

Set DB = Nothing

It can be seen from the reference materials that in most cases in VBS, IsEmpty is still applicable for the initial judgment. But for my usage, because I need to judge whether the object variable is empty again in the end, I still can only use the method of initializing the variable to Nothing, otherwise, IsEmpty judges the empty object and returns False, which is useless.

'---------------------------------------References

1. VBS - Detailed Explanation of Empty Variable Judgment_weixin_30239339's Blog-CSDN Blog

2、https://www.cnblogs.com/wangn/p/3192192.html

Guess you like

Origin blog.csdn.net/jessezappy/article/details/131002947