Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 处理数组以避免错误_Excel_Vba - Fatal编程技术网

Excel 处理数组以避免错误

Excel 处理数组以避免错误,excel,vba,Excel,Vba,在userform1中,我有以下代码 Private Sub cmdOK_Click() Dim i As Long With Me.ListBox2 If .ListCount = 0 Then MsgBox "You Have To Select At Least One Column", vbExclamation: GoTo Skipper ReDim aCols(0 To .ListCount - 1)

在userform1中,我有以下代码

Private Sub cmdOK_Click()
    Dim i As Long
    With Me.ListBox2
        If .ListCount = 0 Then MsgBox "You Have To Select At Least One Column", vbExclamation: GoTo Skipper
        ReDim aCols(0 To .ListCount - 1)
        For i = 0 To .ListCount - 1
            aCols(i) = "[" & ListBox2.List(i, 0) & "]"
        Next i
    End With
Skipper:
    Unload Me
End Sub
在标准模块中,我将ACOL声明为公共的

Public aCols
如果listbox2没有项目,则ACOL变为空,而如果有项目,则ACOL变为数组。。 然后在另一段代码中,我对如何避免错误感到困惑

If UBound(aCols) > -1 Then
如果aCols不是空的,这很好,但是如果aCols是空的,我会遇到错误。。如何处理这两种情况
我只需要避免错误并处理acol,要么它是空的,要么它是数组。

我会使用
函数safeUBound()
,由于OERN,它看起来很难看,但工作正常:

Function safeUBound(a)
    
    safeUBound = -1
    On Error Resume Next
    safeUBound = UBound(a)
    
End Function

另一种解决方案是在代码开头或用户表单初始化时为变量
aCols
分配空数组。

可能会有所帮助。
isArray()
IsEmpty()
都可以用来解决此问题。请看一下,在重新命名之前只需插入
aCols=array()
,然后你可以检查
UBound(aCols)>-1
condition@yasserkalilthanks很多,大家分享这些伟大的想法。