如何在vba宏中检查空数组

如何在vba宏中检查空数组,vba,excel,Vba,Excel,我想检查是否有空数组。谷歌给了我各种各样的解决方案,但都不管用。也许我没有正确地应用它们 Function GetBoiler(ByVal sFile As String) As String 'Email Signature Dim fso As Object Dim ts As Object Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.GetFile(sFile).Open

我想检查是否有空数组。谷歌给了我各种各样的解决方案,但都不管用。也许我没有正确地应用它们

Function GetBoiler(ByVal sFile As String) As String
'Email Signature
    Dim fso As Object
    Dim ts As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.ReadAll
    ts.Close
End Function

Dim FileNamesList As Variant, i As Integer
' activate the desired startfolder for the filesearch
FileNamesList = CreateFileList("*.*", False) ' Returns File names
' performs the filesearch, includes any subfolders
' present the result
' If there are Signatures then populate SigString
Range("A:A").ClearContents
For i = 1 To UBound(FileNamesList)
    Cells(i + 1, 1).Formula = FileNamesList(i)
Next i

SigString = FileNamesList(3)

If Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString)
Else
    Signature = ""
End If

因为
s文件
为空。有什么办法可以避免吗?

这段代码并没有达到您的预期:

If Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If
方法2:使用
FileSystemObject.FileExists
方法

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

If fso.FileExists(SigString) Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

在处理字符串数组时,是否考虑过Join

If Len(Join(FileNamesList)) > 0 Then

我将把这个问题概括起来。 在阵列上测试assingment,并捕获最终错误

Function IsVarArrayEmpty(anArray as Variant)
Dim aVar as Variant

IsVarArrayEmpty=False
On error resume next
aVar=anArray(1)
If Err.number then '...still, it might not start at this index
    aVar=anArray(0)
    If Err.number then IsVarArrayEmpty=True ' neither 0 or 1 yields good assignment
EndIF
End Function

确定它错过了所有负索引或所有>1的数组。。。有可能吗?在weirdland中,是的。

如果对数组函数进行测试,它将适用于所有边界:

Function IsVarArrayEmpty(anArray As Variant)

Dim i As Integer

On Error Resume Next
    i = UBound(anArray,1)
If Err.number = 0 Then
    IsVarArrayEmpty = False
Else
    IsVarArrayEmpty = True
End If

End Function

在写VBA时,我脑海中有这样一句话:“可能很容易,但是……”

以下是我采用它的目的:

Private Function IsArrayEmpty(arr As Variant)
  ' This function returns true if array is empty
  Dim l As Long

  On Error Resume Next
  l = Len(Join(arr))
  If l = 0 Then
    IsArrayEmpty = True
  Else
    IsArrayEmpty = False
  End If

  If Err.Number > 0 Then
      IsArrayEmpty = True
  End If

  On Error GoTo 0
End Function

Private Sub IsArrayEmptyTest()
  Dim a As Variant
  a = Array()
  Debug.Print "Array is Empty is " & IsArrayEmpty(a)
  If IsArrayEmpty(a) = False Then
    Debug.Print "  " & Join(a)
  End If
End Sub

测试空数组的另一种解决方案

if UBound(ar) < LBound(ar) then msgbox "Your array is empty!"
这可能比join()快。(我没有检查负索引)

下面是我的示例,用于过滤2个字符串数组,使它们不共享相同的字符串

' Filtering ar2 out of strings that exists in ar1

For i = 0 To UBound(ar1)

    ' filter out any ar2.string that exists in ar1
    ar2 = Filter(ar2 , ar1(i), False)    

    If UBound(ar2) < LBound(ar2) Then
       MsgBox "All strings are the same.", vbExclamation, "Operation ignored":
       Exit Sub

    End If

Next

' At this point, we know that ar2 is not empty and it is filtered 
'
”从ar1中存在的字符串中筛选ar2
对于i=0到UBound(ar1)
'筛选出ar1中存在的任何ar2.string
ar2=滤波器(ar2,ar1(i),假)
如果UBound(ar2)
使用三重负片:

If (Not Not FileNamesList) <> 0 Then
    ' Array has been initialized, so you're good to go.
Else
    ' Array has NOT been initialized
End If
在VB中,无论出于何种原因,
notmyarray
返回SafeArray指针。对于未初始化的数组,返回-1。您可以
Not
将其与-1异或,从而返回零,如果您愿意的话

               (Not myArray)   (Not Not myArray)
Uninitialized       -1                 0
Initialized    -someBigNumber   someOtherBigNumber

我个人认为,可以修改上面的一个答案来检查数组是否包含内容:

if UBound(ar) > LBound(ar) Then

这可以处理负数引用,并且比其他一些选项花费的时间更少。

我只是简单地将伟大的芯片皮尔逊的代码粘贴到下面。它很有魅力。
这是他的

我希望这有帮助

Public Function IsArrayEmpty(Arr As Variant) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsArrayEmpty
' This function tests whether the array is empty (unallocated). Returns TRUE or FALSE.
'
' The VBA IsArray function indicates whether a variable is an array, but it does not
' distinguish between allocated and unallocated arrays. It will return TRUE for both
' allocated and unallocated arrays. This function tests whether the array has actually
' been allocated.
'
' This function is really the reverse of IsArrayAllocated.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    Dim LB As Long
    Dim UB As Long

    err.Clear
    On Error Resume Next
    If IsArray(Arr) = False Then
        ' we weren't passed an array, return True
        IsArrayEmpty = True
    End If

    ' Attempt to get the UBound of the array. If the array is
    ' unallocated, an error will occur.
    UB = UBound(Arr, 1)
    If (err.Number <> 0) Then
        IsArrayEmpty = True
    Else
        ''''''''''''''''''''''''''''''''''''''''''
        ' On rare occasion, under circumstances I
        ' cannot reliably replicate, Err.Number
        ' will be 0 for an unallocated, empty array.
        ' On these occasions, LBound is 0 and
        ' UBound is -1.
        ' To accommodate the weird behavior, test to
        ' see if LB > UB. If so, the array is not
        ' allocated.
        ''''''''''''''''''''''''''''''''''''''''''
        err.Clear
        LB = LBound(Arr)
        If LB > UB Then
            IsArrayEmpty = True
        Else
            IsArrayEmpty = False
        End If
    End If

End Function
公共函数IsArrayEmpty(Arr作为变量)作为布尔值
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
“我饿了
'此函数测试数组是否为空(未分配)。返回TRUE或FALSE。
'
'VBA IsArray函数指示变量是否为数组,但它不是
'区分已分配数组和未分配数组。这两种情况都会恢复为真
'已分配和未分配的数组。此函数用于测试数组是否实际
“已经分配了。
'
'此功能实际上与IsArrayalLocation相反。
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
暗磅一样长
长得一样
呃,明白了
出错时继续下一步
如果IsArray(Arr)=False,则
'我们没有通过数组,返回True
IsArrayEmpty=True
如果结束
'尝试获取数组的UBound。如果数组是
'未分配,将发生错误。
UB=UBound(Arr,1)
如果(错误编号0),则
IsArrayEmpty=True
其他的
''''''''''''''''''''''''''''''''''''''''''
“在罕见的情况下,我
'无法可靠地复制,错误号
'对于未分配的空数组将为0。
'在这些情况下,LBound为0,而
“UBound是-1。
“为了适应这种奇怪的行为,请测试
'看看LB>UB。如果是,则数组不可用
“分配。
''''''''''''''''''''''''''''''''''''''''''
呃,明白了
LB=LBound(Arr)
如果LB>UB那么
IsArrayEmpty=True
其他的
IsArrayEmpty=False
如果结束
如果结束
端函数

Auth最接近,但他的回答引发了类型不匹配错误

至于其他答案,如果可以的话,您应该避免使用错误来测试某个条件,因为它至少会使调试复杂化(如果是其他原因导致该错误怎么办)

以下是一个简单、完整的解决方案:

option explicit
Function foo() As Variant

    Dim bar() As String

    If (Not Not bar) Then
        ReDim Preserve bar(0 To UBound(bar) + 1)
    Else
        ReDim Preserve bar(0 To 0)
    End If

    bar(UBound(bar)) = "it works!"

    foo = bar

End Function

空数组的简化检查:

Dim exampleArray() As Variant 'Any Type

If ((Not Not exampleArray) = 0) Then
      'Array is Empty
Else
      'Array is Not Empty
End If

您可以使用下面的函数来检查变量或字符串数组在vba中是否为空

Function IsArrayAllocated(Arr As Variant) As Boolean
        On Error Resume Next
        IsArrayAllocated = IsArray(Arr) And _
                           Not IsError(LBound(Arr, 1)) And _
                           LBound(Arr, 1) <= UBound(Arr, 1)
End Function

我在这里看到了类似的答案。。。但不是我的

不幸的是,这就是我将如何处理它。。。我喜欢len(join(arr))>0方法,但是如果数组是一个空字符串数组,它就不起作用了

Public Function arrayLength(arr As Variant) As Long
  On Error GoTo handler

  Dim lngLower As Long
  Dim lngUpper As Long

  lngLower = LBound(arr)
  lngUpper = UBound(arr)

  arrayLength = (lngUpper - lngLower) + 1
  Exit Function

handler:
  arrayLength = 0 'error occured.  must be zero length
End Function

另一种方法是早点做。您可以创建一个布尔变量,并在将数据加载到数组后将其设置为true。因此,您真正需要的只是一个简单的if语句,说明何时将数据加载到数组中。

这里是另一种方法。我在某些情况下使用过它,它很有效

Function IsArrayEmpty(arr As Variant) As Boolean

Dim index As Integer

index = -1
    On Error Resume Next
        index = UBound(arr)
    On Error GoTo 0

If (index = -1) Then IsArrayEmpty = True Else IsArrayEmpty = False

End Function

您可以通过使用JScript的
VBArray()
对象检索元素总数来检查数组是否为空(适用于变量类型、单个或多维数组):

对我来说,每个元素大约需要0.3毫秒+15毫秒的初始化,所以10米元素的数组大约需要3秒。同样的功能可以通过
ScriptControl
ActiveX实现(64位MS Office版本中不提供该功能,因此您可以使用类似的解决方法)。

函数IsVarArrayEmpty(anArray作为变量)作为布尔值 出错时继续下一步 IsVarArrayEmpty=true IsVarArrayEmpty=UBound(anArray)
可能
ubound
崩溃并保持为true,如果
ubound
,则为空

要检查字节数组是否为空,最简单的方法是使用VBA函数
StrPtr()

如果字节数组为空,
strprpr()
返回
0
;否则,它将返回一个非零值(但是,它不是第一个元素的地址)

Dim ar()作为字节
调试。断言strprtr(ar)=0
重拨ar(0到3)作为字节
调试。断言StrPtr(ar)0
但是,它仅适用于字节数组。

Base
if Ubound(yourArray)>-1 then
 debug.print "The array is not empty"
else
 debug.print "EMPTY"
end if
option explicit
Function foo() As Variant

    Dim bar() As String

    If (Not Not bar) Then
        ReDim Preserve bar(0 To UBound(bar) + 1)
    Else
        ReDim Preserve bar(0 To 0)
    End If

    bar(UBound(bar)) = "it works!"

    foo = bar

End Function
Dim exampleArray() As Variant 'Any Type

If ((Not Not exampleArray) = 0) Then
      'Array is Empty
Else
      'Array is Not Empty
End If
Function IsArrayAllocated(Arr As Variant) As Boolean
        On Error Resume Next
        IsArrayAllocated = IsArray(Arr) And _
                           Not IsError(LBound(Arr, 1)) And _
                           LBound(Arr, 1) <= UBound(Arr, 1)
End Function
Public Function test()
Dim Arr(1) As String
Arr(0) = "d"
Dim x As Boolean
x = IsArrayAllocated(Arr)
End Function
Public Function arrayLength(arr As Variant) As Long
  On Error GoTo handler

  Dim lngLower As Long
  Dim lngUpper As Long

  lngLower = LBound(arr)
  lngUpper = UBound(arr)

  arrayLength = (lngUpper - lngLower) + 1
  Exit Function

handler:
  arrayLength = 0 'error occured.  must be zero length
End Function
Function IsArrayEmpty(arr As Variant) As Boolean

Dim index As Integer

index = -1
    On Error Resume Next
        index = UBound(arr)
    On Error GoTo 0

If (index = -1) Then IsArrayEmpty = True Else IsArrayEmpty = False

End Function
Sub Test()

    Dim a() As Variant
    Dim b As Variant
    Dim c As Long

    ' Uninitialized array of variant
    ' MsgBox UBound(a) ' gives 'Subscript out of range' error
    MsgBox GetElementsCount(a) ' 0

    ' Variant containing an empty array
    b = Array()
    MsgBox GetElementsCount(b) ' 0

    ' Any other types, eg Long or not Variant type arrays
    MsgBox GetElementsCount(c) ' -1

End Sub

Function GetElementsCount(aSample) As Long

    Static oHtmlfile As Object ' instantiate once

    If oHtmlfile Is Nothing Then
        Set oHtmlfile = CreateObject("htmlfile")
        oHtmlfile.parentWindow.execScript ("function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}"), "jscript"
    End If
    GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)

End Function
Function IsVarArrayEmpty(anArray As Variant) as boolean
    On Error Resume Next
    IsVarArrayEmpty = true
    IsVarArrayEmpty = UBound(anArray) < LBound(anArray)
End Function
Dim ar() As Byte
Debug.Assert StrPtr(ar) = 0

ReDim ar(0 to 3) As Byte
Debug.Assert StrPtr(ar) <> 0
if Ubound(yourArray)>-1 then
 debug.print "The array is not empty"
else
 debug.print "EMPTY"
end if
Function AryLen(ary() As Variant, Optional idx_dim As Long = 1) As Long
    If (Not ary) = -1 Then
        AryLen = 0
    Else
        AryLen = UBound(ary, idx_dim) - LBound(ary, idx_dim) + 1
    End If
End Function
if (jsonObject("result")("cid").Count) = 0 them
MsgBox "Empty Array"