Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array from Range in Excel VBA

Well I've been struggling with the little bit of code and can't seem to get around it ... I'm trying to get an array from a range of cells, the array however is showing up to be 1 element wide.
Well here's the code:

Dim item As Variant
MsgBox Range("D19:H19").Count    
item = Range("D19:H19").Value
MsgBox LBound(item) & " " & UBound(item)   

as per my understanding item should contain a 2D array... however I'm getting the following result 1st MsgBox prints 5 2nd MsgBox prints 1 1

What's going wrong?

like image 847
Kevin Boyd Avatar asked Oct 10 '09 22:10

Kevin Boyd


People also ask

How do I use an array formula in Excel VBA?

One can use array formulas in two types: If we want to return a single value, use these formulas in a single cell, as in example 1. If we want to return more than one value, use these formulas in Excel by selecting the range of cells as in example 2. Press CTRL + Shift + Enter to make an array formula.

How do I create a dynamic array in VBA?

Create a Dynamic Array in VBAFirst, declare an array with its name. After that, the elements count left the parentheses empty. Now, use the ReDim statement. In the end, specify the count of elements you want to add to the array.


1 Answers

The problem is in LBound and UBound

jtolle was correct about the LBound and UBound.

LBound(item, 2)

UBound(item, 2)

However, item must not be dimmed as an array (you'll get an error).

I think this is what you want

Dim item As Variant
MsgBox Range("D19:H19").Count
item = Range("D19:H19").Value

MsgBox LBound(item, 2) & " " & UBound(item, 2)

For i = LBound(item, 2) To UBound(item, 2)
  MsgBox item(1, i)
Next
like image 57
user1550036 Avatar answered Sep 23 '22 10:09

user1550036