Question

Im trying to assign some values to an array in VBA, the problem is that when I try print each of the values of the array I get one more value than expected because the first value is assigned to the Header.

I have the values like this:

  1. A3 - Category (Header)
  2. A4 - Global
  3. A5 - KAM
  4. A6 - Salesman
  5. A7 - External
  6. A8 - Admin

Here's my code:

Function xyz()
Dim Category as Variant
Set Category = Sheets("Reports").Range("A4:A8")
End Function

The values I get are:

MsgBox Category(0) =Category
MsgBox Category(1) =Global
MsgBox Category(2) =KAM
MsgBox Category(3) =Salesman
MsgBox Category(4) =External
MsgBox Category(5) =Admin

As I understand the Option Base of an Array is set by default as '0', so why is the Category(0) value considering the "A3" cell instead of the "A4" cell?

Était-ce utile?

La solution

Sheets("Reports").Range("A4:A8") is returning a Range object, and you can reference cells in relation to that range. For instance, if you put a sample bit of text in the cell above your header, and you try MsgBox Category(-1), it will show that value.

Have a look at this: http://msdn.microsoft.com/en-us/library/office/ff841096%28v=office.15%29.aspx

Because Item is the default property on the Range class, you can reference it without explicitly using Range.Item (e.g. Category(0) in your example is the same as Category.Item(0))

The Item property -- whether supplied explicitly as in Category.Item(0), or, in your case, implicitly as in Category(0) returns another range representing the cell whose address is relative to your range. That's why if you run my test and call MsgBox Category(-1) with a sample text in cell A2, it will show that text.

FYI: If you want to proof that Category(0) is actually itself a range, run MsgBox TypeName(Category.Cells(0))

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top