根据变量的类型做一些事情

har*_*ryg 3 excel vba excel-vba

我在VBA中有一个通常返回数组的函数.如果没有要返回的内容,则返回一个空变量(b = empty).我有一些代码循环通过数组但如果变量不是数组我得到一个错误.如何创建不会导致自身错误的if语句.我试过了

if not b = empty then
'do the loop
end if
Run Code Online (Sandbox Code Playgroud)

但是这给当b是一个数组同样我得到错误的错误b = null,b = nothing,b(1,1) = ""等.

检查这个的最佳方法是什么?

Tmd*_*ean 6

要测试变量是否为空,请使用IsEmpty函数.

If IsEmpty(b) Then
    Debug.Print "b is Empty"
End If
Run Code Online (Sandbox Code Playgroud)

要测试变量是否为数组,请使用VarType函数.

If VarType(b) And vbArray Then
    Debug.Print "b is an array"
End If
Run Code Online (Sandbox Code Playgroud)

  • 还有`IsArray()`函数,可以用来代替第二个例子. (2认同)