简体   繁体   中英

Extract data from indeterminate range size in Excel

I'm new to VBA, and I'd love some help.

I have a spreadsheet that has a range that will always have 10 columns, but could have X amount of rows. I'm trying to write a VBA script that will iterate over this range and extract the values out of each cell.

For example, if I have 2 rows I need A1, B1, C1..J1 and then I need A2, B2, C2...J2. The next time I could have 5 rows and then another time 3.

How do I setup my loop to make this work?

something like

Dim lastRow as long

lastRow = UsedRange.Rows.Count     'or some other way of determining the last row used

    for i = 1 to lastRow    'loop through all used rows

    'ActiveSheet.Cells(i, 1).value    'column A
    'ActiveSheet.Cells(i, 2).value    'column B
    'ActiveSheet.Cells(i, 3).value    'column C

    next i

You could also use a dynamic named range and loop through that. See this link or google for better examples. Dynamic name ranges are powerful, especially for charts.

For your example you would set the name range reference to;

=OFFSET(Sheet1!$A$1,0,0,COUNT(Sheet1!$A:$A),10) '10 is the width and will go to column J

assuming that column A will have the true max row of the table.

Then;

Dim arr() As Variant

 arr = Range("YourRangeName")

  For x = 1 To UBound(arr,1) 'Finds the max number of rows in the array, UBound(arr,2) finds the total columns.
    'Do some code here where x steps through the array arr
    '  = arr(x, 1) 'column a
    '  = arr(x,2)  'column b 
    '  = arr(x,3) ....     
  Next x

It's almost always better/faster to process as much as you can in code, ie assigning a range in Excel to an Array then loop through the array rather than referencing cells (especially in a loops).

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