如何在VBA中检查表是否为空?

时间:2015-11-12 09:33:51

标签: vba vb6

伪代码如下所示:

@log4j

表的名称类似于“ID_RESULT_1”

1 个答案:

答案 0 :(得分:0)

IsEmpty()函数将返回一个布尔值,表示变量是否已初始化。

如果你想测试一个表是否在其单元格中没有任何内容,你必须循环检查它们。

我提出了这样一个函数," test"您放入的表的维度(仅处理3 dim),然后检查表格的所有单元格:

Public Function IsTableEmpty(anArray As Variant) As Boolean
Dim DimN As Integer, _
    IsEmpty As Boolean

On Error Resume Next
    Debug.Print LBound(anArray, 1)
    If Err.Number > 0 Then GoTo DimN0
    Debug.Print LBound(anArray, 2)
    If Err.Number > 0 Then GoTo DimN1
    Debug.Print LBound(anArray, 3)
    If Err.Number > 0 Then GoTo DimN2
On Error GoTo 0
DimN = 3
GoTo Test

DimN0:
DimN = 0
GoTo Test
DimN1:
DimN = 1
GoTo Test
DimN2:
DimN = 2
GoTo Test

Test:
    Select Case DimN
        Case Is = 0
            If Not IsEmpty(anArray) Then IsTableEmpty = False
            Exit Function
        Case Is = 1
            For i = LBound(anArray) To UBound(anArray)
                If anArray(i) <> vbNullString Then
                    IsTableEmpty = False
                    Exit Function
                Else
                End If
            Next i
        Case Is = 2
            For i = LBound(anArray, 1) To UBound(anArray, 1)
                For j = LBound(anArray, 2) To UBound(anArray, 2)
                    If anArray(i, j) <> vbNullString Then
                        IsTableEmpty = False
                        Exit Function
                    Else
                    End If
                Next j
            Next i
        Case Is = 3
            For i = LBound(anArray, 1) To UBound(anArray, 1)
                For j = LBound(anArray, 2) To UBound(anArray, 2)
                    For k = LBound(anArray, 3) To UBound(anArray, 3)
                        If anArray(i, j, k) <> vbNullString Then
                            IsTableEmpty = False
                            Exit Function
                        Else
                        End If
                    Next k
                Next j
            Next i
        Case Else
            MsgBox "It appears that your table have too many dimensions to be tested by this code!", vbCritical + vbOKOnly
            IsTableEmpty = False
            Exit Function
    End Select
End Function