从Excel中的不确定范围大小中提取数据

我是VBA新手,我很乐意帮忙。

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

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

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

就像是

 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 

你也可以使用一个dynamic命名的范围,并通过循环。 看到这个链接或谷歌更好的例子。 dynamic名称范围非常强大,特别是对于图表。

对于你的例子,你可以设置名称范围引用;

 =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中的范围分配给数组,然后循环访问数组而不是引用单元格(特别是在循环中)。