Handle Error 9 when there is an Empty Array

后端 未结 8 1585
无人共我
无人共我 2021-01-02 17:43

I am writing a script that will loop through an Excel spreadsheet and find if there are duplicates of selected cells. If there are duplicates then the function will return

8条回答
  •  一生所求
    2021-01-02 18:24

    Is your array variant Empty or Empty()?

    'Empty' is an uninitialised variant: IsEmpty(myVar) will return true... And you could be fooled into thinking you have an empty array (which is 'Empty()', not 'Empty' - try to keep up, there will be a short test after this class) because IsEmpty(myArray) returns True, too.

    Dim myVar as Variant      ' this is currently Empty, and Ubound returns an error
    Dim myArray() as variant ' this is currently Empty(), and Ubound returns an error

    Redim myVar(0 to 0) ' this is no longer empty, and has a valid Ubound
    Redim myArray(0 to 0) ' this is no longer empty, and has a valid Ubound

    A reliable way to check myVar is TypeName(myVar) - if it's an array, the name contains brackets:

      
    If Instr(Typename(myVar), "(") > 0 then  
    
        ' we now know it is an array  
        If Not IsEmpty(myVar) Then  
    
           ' We can now check its dimensions  
            If Ubound(myVar) > 0  
                 ' insert error-free code here  
            Endif  
    
        Endif  
    
    Endif  
    
    

    The full answer is 'Detecting an array variant in Excel VBA' on Excellerando.

提交回复
热议问题