Vba 매크로를 빈 어레이입니다 확인할지 방법

I want to check for 빈 배열입니다. 구글 내게 준 다양한 솔루션은 물론 아무것도아니야 했다. 어쩌면 나는 올바르게 적용하기 없습니다.

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

여기서 ',' 안 '어레이입니다 비워집니다 경우 피렌임슬리스트 제바일레르 (식스트링)' 라는 확보하십시오 전혀. 이 때 ',' 빈 '도' 어레이입니다 비워집니다 피렌임슬리스트 식스트링 페이징됩니다 제바일레르 비어 있는 ' ()' 기능을 구체화하십시오. 저도 한 행의 오류

Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)

이후 '스피리' 비어 있습니다. 그런 상황을 피하기 위한 어떤 식으로?

질문에 대한 의견 (1)

다룰 때 문자열으로 어레이이며 참가하십시오 고려해 본 적이 있으십니까?

If Len(Join(FileNamesList)) > 0 Then
해설 (8)

함께 "트리플 제외어:

If (Not Not FileNamesList)  0 Then
    ' Array has been initialized, so you're good to go.
Else
    ' Array has NOT been initialized
End If

스피커에만:

If (Not FileNamesList) = -1 Then
    ' Array has NOT been initialized
Else
    ' Array has been initialized, so you're good to go.
End If

Vb, 있는 것은 ',' 어떤 이유로든 myArray 되돌려줍니다 사피어리 포인터입니다. 이 경우 되돌려줍니다 비초기화 어레이에는 - 1. 배타적 논리합 (xor) - 1 이 아닌 'it with you can', 즉, 카타시안 돌아갈 수도 있습니다.

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

[출처] (http://www.vbforums.com/showthread.php? p = 4040234&amp 보기전체 = 1 # post4040234 654880-How-do-I-tell-if-an-array-is-quot-empty-quot&;)

해설 (3)

39 의 모든 기능을 사용할 경우, ll 점심시간요 어레이에서는 it& 니며:

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
해설 (3)

아 여기 있는 유사 답안. 내거냐 수는 없습니다.

This is how I am 운포르투나틀리 이를 처리할 수 있는 것입니다. 내가 &gt 같은 렌 (join (도착). 하지만, 이 경우, 0 외곽진입 wouldn& # 39 는 왕티스트링스 배열입니다 어레이입니다 빗나갔다.

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
해설 (0)

Vba 를 쓸 때 좁히어 로만스였나 마디였나 in my head. 그렇게 쉽게, but.&quot &quot, 될 수 있다.

다음은 내가 이를 채택했다.

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
해설 (2)

이 코드는 doesn& # 39, t 뭘 기대할 수 있습니다.

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

전달하는 경우 빈 문자열 (&quot &quot, ',') '를' 또는 '브븐울스트링 Dir' 이 첫 번째 파일 이름을 반환되므로 현재 디렉토리에 패스 (path 반환되었습니다 쿠르트르 $ '에서'). 따라서 '식스트링' 비워집니다 너회의 "만약 '조건' 진정한 '는' 디렉터리 '비어 있지 않은 반환되므로 평가할 수 있기 때문에 문자열 (첫 번째 파일 이름을 현재 디렉토리임)' 및 '제바일레르 될 것 이라고 합니다. 만일 '', '를 호출하는 식스트링 비워집니다 펠릭스 소스제피리' 실패합니다.

두 가지 조건을 확인해야 합니다 ',' isn& 변경하십시오 식스트링 피레시스티모비치스피리시스테스 '방법' 대신 '비어 있거나, t # 39 사용하여 파일의 경우, 디렉터리' 확인을 위해 존재합니다. 정확하게 사용할 수도 있습니다. '는' Dir 까다로운 셨으며 않으므로 개인적으로 할 것으로 예상하고 있습니다. ',' over '때문에' s no there& Dir 스크리프팅스피리시스티모비치 사용하게 된다 # 39 재밌는 비즈니스 ('피레렉시츠' 되돌려줍니다 'True' 파일의 경우 존재하며, 뭐, '거짓' doesn& 경우 # 39, t). # 39 의 경우는 '의도' 를 what& 피레렉시츠 코드에 비해 훨씬 더 확실히요 Dir '의'.

  • 방법 1. * '는' 비어 있지 않은 첫 식스트링 있는지 확인하십시오.
If SigString  "" And Dir(SigString)  "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If
  • 방법 2: '피레시스티모비치스피리시스테스 방법을 사용하여' *
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

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

아래 코드를 직접 붙여넣기 나는 단순히 위대한 칩 피어슨. 작동하잖아 한 들었다.

39 의 here& 그의 [페이지에서 어레이입니다 총괄하였습니다] (http://www.cpearson.com/excel/vbaarrays.htm).

이렇게 하면 좋겠다.

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
해설 (1)

그러나 그의 가장 가까운 오토메이티드 문자 인증 sanlight 던지는 불일치입니다 오류:.

이와 함께 사용하지 않아야 합니다 다른 답을 오류가 조건에 대한 테스트하려면 수 있다면, 이 때문에 최소한 디버깅하지 된다 (와일드링이 아무도요 인해 뭔가 오류가).

39 의 완료하십시오 here& 단순 솔루션:

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
해설 (0)

단순화됨 확인할지 빈 어레이입니다:

Dim exampleArray() As Variant 'Any Type

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

답변 # 39, ahuth& 기반으로 한다.

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

확인할지 빈 스토리지였습니다. 'is_empty 라일런' (some_array) = 0 =

해설 (0)
Public Function IsEmptyArray(InputArray As Variant) As Boolean

   On Error GoTo ErrHandler:
   IsEmptyArray = Not (UBound(InputArray) >= 0)
   Exit Function

   ErrHandler:
   IsEmptyArray = True

End Function
해설 (2)

아래의 기능을 사용할 수 있는 변형 또는 문자열 어레이입니다 비워집니다 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) 
해설 (0)

또 다른 방법은 약간만이라도 할 것이다. It true 로 설정하고 나면 부울입니다 변수를 만들 수 있는 데이터를 로드하는 스토리지와의. 그래서 정말로 필요한 것은 단순한 경우 기술서임을 경우 모든 데이터를 로드하는 꽂으십시오 어레이입니다.

해설 (0)

여기 다른 길일. 이 경우에 따라 및 it& 사용한 # 39 의 작업 중.

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
해설 (0)
Function IsVarArrayEmpty(anArray As Variant) as boolean
    On Error Resume Next
    IsVarArrayEmpty = true
    IsVarArrayEmpty = UBound(anArray) < LBound(anArray)
End Function

어쩌면 ',' 진정한 '충돌 및 it 는 베운드 아웃하기로 베운드 &lt. # 39 의 it& 라보런드 '빈

해설 (0)

바이트 배열을 비워집니다 여부를 확인하려면, VBA 를 사용하는 것이 가장 간단한 방법은 함수 (), /code&gt &lt 스트라프트 code&gt <;;).

이 경우,,, /code&gt &lt 바이트입니다 어레이입니다 비워집니다 &lt code&gt 스트라프트 () &lt 되돌려줍니다 code&gt 0&lt /code>;;;; 그렇지 않으면 비제 반환 값 (그러나 it& # 39 의 &lt b&gt not&lt /b>;;; 주소 첫 번째 요소).

Dim ar() As Byte
Debug.Assert StrPtr(ar) = 0

ReDim ar(0 to 3) As Byte
Debug.Assert StrPtr(ar)  0

그러나 국한됨 수행됨 바이트입니다 어레이입니다.

해설 (0)

그 카운트입니다 확인할 수 있습니다.

여기서 cid 배열입니다.

if (jsonObject("result")("cid").Count) = 0 them
MsgBox "Empty Array"

이렇게 하면 좋겠다. Have a nice day!

해설 (0)

만약 어레이입니다 비워집니다 검색하여 카운트입니다 총 요소를 통해 확인할 수 있습니다 ' ()' 의 jscript& # 39 바바라이 객체에는 수행됨 어레이에는 변형 유형, 단일 또는 다차원):

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

가져다줄래요 정도 걸리기 때문에, 각 요소의 + 0.3 므스크 15 시간을 약 3 초 밀리초 초기화하지 배열에 10M 요소를 동일한 기능을 통해 스크리프트콘트럴 구축할 수 있는 '' ActiveX (이 기능을 사용할 수 없습니다, 64 비트 버전을 사용할 수 있도록 MS Office 같은 해결하십시오 [이] (https://stackoverflow.com/a/38134477/2165759)).

해설 (1)

개인적으로 생각하는 답은 위에 있는지 확인하는 어레이에는 내용을 수정할 수 있습니다.

if UBound(ar) > LBound(ar) Then

이 핸들이 음수가 아닌 참조이고 단시간에 일부 다른 옵션.

해설 (1)

[질문] # 39, ll 일반화할 i& 문제 및 의도한 대로. 테스트 아싱망 스토리지에 and catch 최종 오류

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

모든 제외어 indexe 또는 모든 &gt 실패와 어레이에는 합니다. 1. 에로남이네 것으로 보인다. 의 베르트랑, 예.

해설 (1)