Why am I having issues assigning a Range to an Array of Variants

前端 未结 3 2008
有刺的猬
有刺的猬 2020-11-27 18:21

I am having a few problems with some VERY simple lines of code. Let me detail the facts and see if anyone else can replicate this behavior. If any one can replicate I would

3条回答
  •  情书的邮戳
    2020-11-27 19:02

    Let me clarify my comment.
    It can't fit to comment to i post it as answer just to at least clear my point.

    Dim arr As Variant '~~> you declare arr as Variant as what Tim said
    

    what does it mean?
    It means that arr can take on any form (eg. integer, string, array, object and all the other Variable Type)

    Dim arr() as Variant '~~> you declare arr() as array which may contain Varying `Data Type`
    

    what does it mean?
    It means that arr() array variable can store different Data types.
    That excludes Objects or Collection of Objects.

    Now, why the following works:

    1. Dim arr() As Variant: arr = Range("A1:A10")
    2. Dim arr() As Variant: arr = Sheet1.Range("A1:A10")
    3. Dim arr() As Variant: arr = Sheets("Sheet1").Range("A1:A10").Value
    

    This also works:

    4. Dim arr() as Variant
       Dim rng as Range
    
       Set rng = Sheets("Sheet1").Range("A1:A10")
       arr = rng
    

    Above works because you are not trying to assign Collections of Objects into an array.
    Instead, you are assigning a specific entity or value.
    Range is an object but not a Collection of Objects.
    No.1 example is direct without accessing Sheets Collection Object.
    Same is true with
    No.2 since you work with Sheet1 which is a Sheet Object but not Collection of Sheet Objects.
    No.3 is self explanatory, you assign .Value to an arr array.
    No.4 works because rng is already a Range object by Set which again is not a Collection of Objects.

    So this:

    Dim arr() As Variant
    
    arr = Sheets("Sheet1").Range("A1:A10")
    

    doesn't work because Excel will read this as trying to assign Object from Sheets Collection of Objects and thus error occurs.
    I hope this makes sense a bit.

提交回复
热议问题