2012-06-26 47 views
1

我是VBA的新手,我很乐意提供帮助。从Excel中的不确定范围大小提取数据

我有一个电子表格,其范围始终为10列,但可以有X行数量。我正在尝试编写一个VBA脚本,它将遍历这个范围并从每个单元格中提取值。

例如,如果我有2行,我需要A1,B1,C1..J1,然后我需要A2,B2,C2 ... J2。下一次,我可以有5行,然后又一次3.

如何设置我的循环,使其工作?

+0

确定最后一次使用的行:http://stackoverflow.com/a/10642588/829571 – assylias

+0

如果不是列特定的行数,您还可以使用UsedRange.Rows.Count来确定最后一行。 –

+0

如何将Range(“A1”),CurrentRegion.Value'赋值给Variant变量,然后遍历它?那可能吗? – JimmyPena

回答

0

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 
+0

非常好!我在上面提到的“UsedRange.Rows.Count”中使用了它。 – Mark

+0

我很高兴你发现它很有用。正如Siddharth所说,UsedRange.Rows.Count不是查找最后一行数据的好方法。 – Sam

0

你也可以通过使用动态命名的范围和循环。请参阅link或google以获得更好的示例。动态名称范围功能强大,特别适用于图表。

对于您的示例,您可以将名称范围引用设置为;

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

假设列A将具有该表的真正最大行。

然后;

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 

它几乎总是更好/更快的处理尽可能多,你可以在代码,即通过阵列分配在Excel中的范围到数组然后循环而不是参照细胞(尤其是在一个循环)。