vb6.0 判斷數組爲空

方法一:Error方法

就是採用通用的錯誤捕獲功能

On Error Goto 行號       '遇到錯誤,轉到行號處處理

On Error Resume Next '忽略錯誤,繼續執行

On Error Goto 0           '強制取消錯誤捕獲功能

Function IsNotEmpty(ByVal sArray As Variant) As Boolean '判斷數組是否爲空

        Dim i     As Long

        IsNotEmpty = True

        On Error GoTo lerr:

        i = UBound(b)

        Exit Function

lerr:

        IsNotEmpty = False

End Function

方法二:CopyMemory方法

VB的數組都是安全數組,通過訪問一個結構來確定 數組內容保存位置,上標下標和維數

安全數組結構的地址可以用

Private Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (ByRef Ptr() As Any) As Long

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" _

             (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)

安全數組的頭兩位就保存着維數信息

Option Explicit

Private Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (ByRef Ptr() As Any) As Long

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)

Private Sub Form_Load()

    Dim MyArr() As Long

    Dim pMyarr As Long

    Dim nDims As Integer

    '從數據指針得到SafeArray結構的指針

    CopyMemory pMyarr, ByVal VarPtrArray(MyArr), 4

    If pMyarr = 0 Then

        MsgBox "這個數組是空數組"

        '再從這個指針所指地址的頭兩個字節取出cDims

        CopyMemory nDims, ByVal pMyarr, 2

        MsgBox "這個數組有" & nDims & "維"

    End If

End Sub

方法三:使用api函數safearraygetdim()的返回值,返回值值<=0,說明數組元素個數爲0或者數組還沒有初始化.

SafeArrayGetDim用來判斷一個數組的維數,該函數在MSDN中定義爲:

UINT SafeArrayGetDim(

  SAFEARRAY FAR* psa 

轉換維VB中的語法格式爲:

Public Declare Function SafeArrayGetDim Lib "oleaut32.dll" (ByRef saArray() As Any) As Long

如果數組已經初始化,則返回非0,否則返回0。

'API判斷數組爲空或沒有初始化

Sub diag()

Dim msg As String

Dim arr1() As String, arr2() As String, arr3() As Date, arr4() As Date, arr5() As Range, arr6() As Range

msg = "arr1 " & IIf(SafeArrayGetDim(arr1) > 0, "數組不爲空!", "數組爲空!")

arr2 = Split("一、二、三、四、五、六", "、")

msg = msg & vbCrLf & "arr2 " & IIf(SafeArrayGetDim(arr2) > 0, "數組不爲空!", "數組爲空!")

msg = msg & vbCrLf & "arr3 " & IIf(SafeArrayGetDim(arr3) > 0, "數組不爲空!", "數組爲空!")

ReDim arr4(1 To 100)

msg = msg & vbCrLf & "arr4 " & IIf(SafeArrayGetDim(arr4) > 0, "數組不爲空!", "數組爲空!")

ReDim arr6(1 To 256, 1 To 65536)

msg = msg & vbCrLf & "arr5 " & IIf(SafeArrayGetDim(arr5) > 0, "數組不爲空!", "數組爲空!")

msg = msg & vbCrLf & "arr6 " & IIf(SafeArrayGetDim(arr6) > 0, "數組不爲空!", "數組爲空!")

MsgBox msg

End Sub

方法四:使用cstr(Join(list[, delimiter]))函數的返回值是否不等於""

將delimiter參數設置爲""

例如:if (cstr(join(arr,""))) = "" then msgbox "arr 數組爲空或者尚未初始化"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章