如何使用VBA设置单元格的dynamic范围?

比方说,我有一个循环写,但需要设置大量的范围,它的工作。 如何设置一个范围以包含跨工作表分布的单元格。 比方说,在每一行中,我想从列J,列S,列T ….一直到列GB(每列之间5列)中select单元格。 伪脚本我有这样的东西:

Sub CountPubs() Dim i, j As Long Dim Quant As Range i = 2 j = 5 While i <= 400 Set Quant=Cells("I" & i),("I+j" & i),("I+2j" & i)... 

所以Set线是可怕的。 每次满足条件时,循环本身都会增加i,但是我希望按照Quant定义,在第i行上的36个单元也会增加。 我怎样才能以这种方式完成Set Quant线?

编辑:在我的testing中,我甚至不能得到一个更简单的版本。 如果我只是把这个做到T,我想这个剧本会是:

 Sub CountPubs() Dim Count As Range Dim i As Long Dim Publications As Range i = 2 Set Count = Range("C" & i) Set Publications = Range("I" & i), ("O" & i), ("T" & i) 

但是,这给我一个编译错误,错误的参数数量或无效的属性分配。 我在这里错误地定义了最后一个范围吗?

您将要使用联合方法来构buildQuant范围。

 Dim i As Long, rw As Long, Quant As Range With ActiveSheet rw = 2 'this will work on row 2 from J to GB Set Quant = .Cells(rw, "J") 'seed the target range 'Set Quant = .Cells(rw, "J").Resize(400, 1) 'optional 400 rows deep For i = .Columns("J").Column To .Columns("GB").Column Step 5 Set Quant = Union(Quant, .Cells(rw, i)) 'Set Quant = Union(Quant, .Cells(rw, i).Resize(400, 1)) 'optional 400 rows deep Next i Debug.Print Quant.Address(0, 0) End With 

我已经包含了400行深的选项行。

您可以使用Union方法来创build不相邻的单元格范围。

在你的情况下,你可以使用下面的:

 Sub unionCells() Dim i, j As Long Dim Quant As Range i = 2 j = 5 While i <= 400 Set Quant = Union(Cells(9, i), Cells(9 + j, i), Cells(9 + 2 & j, i)) Wend End Sub 

你也可以看到关于使用union的这个答案 。

联合函数的另一种方法是创build一个范围数组,并在您的循环中,将每个新的单元添加为数组中的下一个项目。

有一些显而易见的缺点,例如,您将无法将范围作为一个整体进行引用,并且在开始向其中添加项目之前,您需要首先确定数组的大小。 但是,它有一个好处,它可以让你通过引用一个索引号来引用每个单元格。 如果您按顺序跟踪单元格,这可能会很有用,并且您只想通过引用该顺序一次引用单元格1。 这将工作如下[一些片段从@Jeeped上面被盗]:

 Dim i As Long, rw As Long, Quant() As Range, QuantSize As Long With ActiveSheet For i = .Columns("J").Column To .Columns("GB").Column Step 5 QuantSize = QuantSize + 1 'builds in the size of the array Next i ReDim Quant(1 To QuantSize) 'Resizes the array to match the total length above rw = 2 'this will work on row 2 from J to GB For i = .Columns("J").Column To .Columns("GB").Column Step 5 Set Quant(i) = .Cells(rw, i) Next i End With