简体   繁体   中英

VBA: reading Excel range into an object array

How do I read an Excel range into an object array?

To clarify, for this Excel range of 6 cells...

John    Roberts    56
Sam     Alito      52

and this class...

Class supremes      
Public firstName        
Public lastName     
Public age  
Dim supreme As New supremes 

I'd like to read the Excel range into an array of supreme such that:

arr(1).firstName = "John"   
arr(2).age = 52 

For a standard array, this is done with a single assignment...

arr = range("supremes")

Is there a similar command to populate the object array?

There isn't any special way to read data into an array object. You just need to roll your own code.

dim i as long
dim rData as range
dim vData as variant

set rData=selection

vData=rData

for i=1 to ubound(vdata)
  arr(i).FirstName=vdata(i,1)
  arr(i).LastName=vdata(i,2)
  arr(i).Age=vdata(i,3)
next i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM