You are on page 1of 1

Products Search… 1 1

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

PUBLIC Asked 7 years, 2 months ago Active 4 years ago Viewed 24k times

Questions
I am having a few problems with some VERY simple lines of code. Let me detail the facts and see
Tags The Overflow Blog
if anyone else can replicate this behavior. If any one can replicate I would like to get an explanation
Users 26 of why it is happening. Introducing The Key

FIND A JOB Podcast 326: What does being a “nerd”


So lets me start with a very simple line of code THAT WORKS:
even mean these days?
Jobs

Companies 8 Dim arr() As Variant Featured on Meta


arr = Range("A1:A10")

TEAMS Stack Overflow for Teams is now free for


this does as expected, arr is assigned the Values of A1:A10 up to 50 users, forever
Stack Overflow for
Teams – Collaborate Announcing “The Key™” - copy paste like
and share knowledge
now why won't the following line of code work? you've never done before
with a private group.
Dim arr() As Variant Linked
arr = WorkSheets("Sheet1").Range("A1:A10")

5 VBA, Excel, use Range to fill 2D-Array


I get a Run-Time Error '13' Type mismatch, even though the same range was successfully
4 2 Dimensional array from range
assigned to the array, just without the Worksheet value.
6 Why should I use the DIM statement in
Create a free Team But VBA or Excel?

What is Teams? 5 Does .Value = .Value act similar to


Dim arr As Variant Evaluate() function in VBA?
arr = Worksheets("Sheet1").Range("A1:A10")
1 What is the default return type for functions
in VBA?
And -5 Difference between `Range`,
`Range.Cells`, `Range.Rows`, etc.,
“subtypes”
Dim arr() As Variant
arr = Application.Transpose(Application.Transpose(Worksheets("Sheet1").Range("A1:A10"))) 2 Excel VBA Type Mismatch Error passing
range to array

3 “Method or Data Member Not Found” when


DOES WORK Dim'ing Worksheet as Worksheet but not
Variant
Now before you answer please let me give you some more facts.
4 Default Range property produces
unexpected results
Dim arr() As Variant
1 Reading A Worksheet Range To A VBA
arr = Worksheets(1).Range("A1:A10")
Array, get script out of range error

See more linked questions


Does Not Work

and using Sheets in place of Worksheets also all give the same error. Related

I have made sure it is the same sheet as the active referenced sheet by using 1906 Why is using “for…in” for array iteration a
bad idea?
Range("A1:A10").Worksheet.Name Following the working code and it indeed says Sheet1 in the
output. 0 Guidance required for VBA code to copy
data from multiple worksheets to another
worksheet
No other workbooks are open so it can't be referencing another workbook either.
0 Populating an array with named range on a
Now this last bit of code only adds to my confusion as it totally works! specific worksheet

2 Copy cells to active worksheet from a


Dim arr() As Variant defined RANGE of SHEETS
Dim SampleRange As Range
0 how to prevent vba to convert the value
type while copy and pasting?
Set SampleRange = Worksheets("Sheet1").Range("A1:A10")
arr = SampleRange 1 Delete columns across multiple worksheets
based on column header value

So using the SAME RANGE defined the same way on the same sheet now works when I assign it 0 Cross referencing a cell with sheet number
to a Range Variable. and use that! And as expected this works with both the WorkSheets and
Sheets function regardless of how I define the sheet (I can use the index or the Name of the Hot Network Questions
worksheet and all work fine)
Taking over another fired developers role

If it helps anyone, I am testing this with Excel 2007 on a Windows XP machine. I have not yet How do the functions Reap and Sow actually work
behind the scenes?
tested it on any other machines but I plan to test on 2003 and 2010 on Windows 7 and 8, just
haven't had the chance yet. Missed apple pruning window

What is the rationale behind making it illegal to


UPDATE: Not 100% sure if this is the same exact issue as with the array but from a shallow view it hand out water to voters in line in Georgia?
seems to be: Poor man's JIT using nested lambdas

How does a blockchain relying on PoW verify that


Range("B1:B3") = Range("A1:A3") a hash is computed using an algorithm and not
made up by a human?

Can I ask to "audit"/"shadow" a position, if I'm not


The above code will not work, even if A1:A3 is populated, dates, numeric values, strings, formula selected?
anything, it will write blanks into B1:B3 The correct way to draw this fractal

But Books on Philosophy of Math by Mathematicians

Find the largest number that Bash arithmetic can


handle?
Range("B1:B3").Value = Range("A1:A3").Value
Why are all the MOSFETs' drains connected
together and to nowhere else?
And Is it safe to share .git folder of a public repo?

Classification of vector spaces with a quadratic


Range("B1") = Range("A1") form and an order n automorphism

What limits a PIN diode or varicap from being


used in a "Software Defined [Radio] Filter"?
does work!
How does it feel like to be outside a flying
airplane?
Also working is:
Why is ⾏く used in the sentence "すぐに出て⾏
け"?
Range("B1:B3") = Application.Transpose(Application.Transpose(Range("A1:A3")))
How much of my mortgage do I need to pay off for
the FICO "Proportion of loan balances to loan
amounts is too high" reason code to disappear?
arrays vba excel When do we use "any" with countable nouns?

Looking for a graphic novel (Brin-inspired?):


Share Edit Follow edited Jan 30 '15 at 14:20 asked Jan 27 '14 at 16:56 investigator who can self clone. Futuristic setting,
spacious Modernist interiors
pnuts user2140261
54.5k 9 72 122 7,307 7 28 43 Mountain bike tyre at road bike pressure

Symmetric random walk on a cube

Four TeX processors (as described in TeX by


1 I'm thinking this has something to do with the default behavior of referring to Range . Often Range(X) Topic)
can be used to refer to the contents of the range X . If we instantiate it as the Range property of a
Worksheet, I'm thinking we refer to that hardcoded "Range-ness" of it. However, this does not explain why How can I make my class immune to the "auto
setting it to a variable bypasses it. Hopefully, someone can come along and explain it. Value solves it value = copy of proxy" landmine in C++?
for me either way, though. Win7, XL2010. – NullDev Jan 27 '14 at 17:09 Plausibility of an atmosphere on the furthermost
planet of a solar system
5 I have no idea why the second method doesn't work when the first does. This is not typically how you'd
assign a range directly to an array though: usually you'd declare arr as Variant , and not as an array
of variants, which is what you have here. Using just a regular Variant you will not see this behavior. Adding Question feed
.Value to the end of your second method also fixes the problem, so must be something related to
relying on the default property being different between the two approaches. – Tim Williams Jan 27 '14 at
17:11

1 @user2140261, changing Dim arr() As Variant to Dim arr As Variant fixes problem for me
and arr = Worksheets(1).Range("A1:A10") works fine! – Dmitry Pavliv Jan 27 '14 at 17:14

2 @simoco is correct. Removing () and just leaving Dim arr As Variant will correct the issue on
the Worksheets... part. Now, how to understand all of this. :D – NullDev Jan 27 '14 at 17:17

1 @simoco Yeah dimming it in that manner also fixes it for me, for the record the article I was speaking of
was Here – user2140261 Jan 27 '14 at 17:17

Show 22 more comments

3 Answers Active Oldest Votes

No it is not a bug.

32 The point is that Value is the default property of the Range Object, so why isn't it implicitly
used? Did you have a look at the question I linked? (FROM CHAT)

The experts posting previous answers have already explained very well in details. I will keep the
explanation to minimal and hence let me know if you still have any questions.

Let's understand our objects first. I created this small table which clearly shows what are we
handling so that there is no confusion.

You could also add a Watch to see the Type for a particular object as shown in the pic below.

So when you say

arr = Range("A1:A10")

Excel knows that the default property is .Value . However in other case, it doesn't know because
Excel is not a mind reader or let's say intelligent enough to understand whether you want to use
Worksheets("Sheet1").Range("A1:A10") as a Range or a Variant

Once you explicitly specify your object as a Range then Excel knows what you want. For example
this works.

Dim arr() As Variant


Dim Rng As Range
Set Rng = Worksheets("Sheet1").Range("A1:A10")
arr = Rng

Share Edit Follow edited Jan 18 at 12:34 answered Jan 28 '14 at 16:56
Community ♦ Siddharth Rout
1 1 136k 15 189 235

1 +1 for the Watch to show the Type, I had been using TypeName and VarType, and both returned Range
for every item. – user2140261 Jan 28 '14 at 17:09

1 Hope that clarifies when .Value is the default property and when it is not :) – Siddharth Rout Jan 28 '14
at 17:11

plus one for because Excel is not a mind reader or let's say intelligent enough .
this is the most important fact. – L42 Jan 29 '14 at 0:38

Why would Worksheets("Sheet1").Range("A1:A10") be treated as a variant, but not Range("A1:A10")? –


Excel Developers Apr 17 '15 at 8:42

Add a comment

Let me clarify my comment.


It can't fit to comment to i post it as answer just to at least clear my point.
3
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.

Share Edit Follow answered Jan 28 '14 at 5:04


L42
18.5k 10 37 62

Both Range("A1:A3") and Sheets("Sheet1").Range("A1:A3") are Range Objects


regardless of what you say this is a fact. You can type cast them in many ways and every way that you
test both versions they will return a Range type. And because of that BOTH should either implicitly work
or fail. Also, you are wrong by stating that Sheets("Sheet1") returns a Collection of Sheet Objects.
Sheets itself IS a collection of sheets and when passing the parameter of a sheet name the Sheets
Class returns a Sheet object not its entire collection. Like Mehow I think its just a bug. – user2140261
Jan 28 '14 at 13:44

I think @Siddharth Rout already clear this in his post. Sorry i was sloppy in the way i explain things. :) But
i'm glad somehow we cleared our confusion. – L42 Jan 29 '14 at 0:41

Add a comment

I would say an Array of Something is not the same as a Something, since this Something can
be an Array of some other things. If you define something as an Array, what you assign to it has
2 to be an Array, be it an Array of Number, Text, Range, Chart objects, etc.

When things work that we don't expect, I believe it's the built-in data type conversion that makes
things easy for us most of the time. This conversion may have to be a direct object, not properties
of an object.

For example, Rows and Cols are of type Long, but you can throw the Byte/Double type at it:

Cells(1,1.5) gives value of Cells(1,2)

You don't have to convert 1.5 to Long; Excel does it all in background for you.

When you define an array of something and assign things to it, Excel does type matching behind
the scene and set values when possible.

Check with these in the Immediate window:

?typename(Range("A1:A10").Value) gives you Variant() <-- this is why it works on Dim


arr() As Variant without any issues

?typename(Range("A1:A10")) gives you Range . But when you assign it to arr where Dim
arr() As Variant , Excel converts the Range to an Array using the values of that Range.

However, Excel seems to fail converting if it doesn't have direct access to the object, unless you
created memory for it. For example:

Dim arr() As Variant, oRng As Range


Set oRng = Range("A1:A10")
arr = oRng
Set oRng = Worksheets("Sheet1").Range("A1:A10")
arr = oRng

The above code is all fine, but it cannot convert and assign arr =
ThisWorkbook.Worksheets("Sheet1").Range("A1:A10") in one go, unless you throw an array to
it ( ThisWorkbook.Worksheets("Sheet1").Range("A1:A10").Value is of type Variant()).

Share Edit Follow edited Mar 28 '17 at 13:42 answered Jan 28 '14 at 6:27
TylerH PatricK
18.9k 48 65 85 6,177 1 16 24

Plus one. Again it boils down to @Tim Williams statement that declaring a variable as variant is different
from declaring an array variable of variant type. – L42 Jan 28 '14 at 6:42

1 THIS IS FALSE! I don't get why you can't understand that. Because ?
typename(Worksheets("Sheet1").Range("A1:A10")) ALSO gives you Range yet it does NOT
work with Dim arr() As Variant , it's kidn of annoying how many people can take information with
no actual proof of facts to back up the statement, besides saying it is what it is. Then use a statement
thinking it is a factual statement. – user2140261 Jan 28 '14 at 12:36

Add a comment

Your Answer

Links Images Styling/Headers Lists Blockquotes Code HTML Tables Advanced help

Post Your Answer

Not the answer you're looking for? Browse other questions tagged arrays vba excel or ask your
own question.

STACK OVERFLOW PRODUCTS COMPANY STACK EXCHANGE Blog Facebook Twitter LinkedIn Instagram
NETWORK
Questions Teams About
Technology
Jobs Talent Press
Life / Arts
Developer Jobs Directory Advertising Work Here
Culture / Recreation
Salary Calculator Enterprise Legal
Science
Help Privacy Policy
Other
Mobile Terms of Service
Disable Responsiveness Contact Us
Cookie Settings
site design / logo © 2021 Stack Exchange Inc; user contributions
Cookie Policy licensed under cc by-sa. rev 2021.4.1.38970

You might also like