如何在不使用数组的情况下访问范围variables的非连续内容

RE-RECLARIFIED:我是一个优秀的VBA新手,所以忍受着我…

我需要访问非连续范围variables中的单个单元格并更改其值。

有没有顺序的方式来循环通过一个非连续的范围variables?

例如:

rng = Range("d1:d6, d12") 

这个范围有7个单元格,但是我不能在这个范围内循环单元格,因为“单元格”function把第7个单元格看作是d7。 或者我可以以其他方式?

我不能使用FOR EACH,因为我需要使用范围本身以外的其他variables来跳过范围并更改其中的值。

所以这里是我正在做的一个不起作用的例子:

 ' If I could access a range like an array rng(1) = Application.InputBox(prompt:="Enter customer's name: ", Title:="CUSTOMER NAME", Type:=2) rng(2) = Application.InputBox(prompt:="Enter travel out date: ", Title:="TRAVEL OUT DATE", Type:=1) rng(3) = Application.InputBox(prompt:="Enter travel back date: ", Title:="TRAVEL BACK DATE", Type:=1) rng(4) = Application.InputBox(prompt:="Enter number of technicians: ", Title:="TECHNICIANS", Type:=1) rng(5) = Application.InputBox(prompt:="Enter number of engineers: ", Title:="ENGINEERS", Type:=1) rng(6) = Application.InputBox(prompt:="Enter location: ", Title:="LOCATION", Type:=2) rng(7) = Application.InputBox(prompt:="Enter todays date: ", Title:="TODAY'S DATE", Type:=1) 

我不想使用一个数组,因为我不只是想单独处理单元格的值,我想改变单元格中的值,并将其反映在该单元格中,而不必经历重装过程数组内容进入了范围,无论如何,这再次给我提出了同样的问题。

有什么build议么?

嗯,这个怎么样?

 Sub test() Dim Arr() As String ' dynamic array, ReDim Arr(Selection.Count) ' ... properly sized i = 0 For Each c In Selection i = i + 1 Arr(i) = c.Address ' save each cell address Next c ' now we can reference the cells sequentially Range(Arr(1)) = Application.InputBox(prompt:="Enter customer's name: ", Title:="CUSTOMER NAME", Type:=2) Range(Arr(2)) = Application.InputBox(prompt:="Enter travel out date: ", Title:="TRAVEL OUT DATE", Type:=1) ' ... End Sub 

如果您在电子表格中突出显示要访问的单元格,则可以这样做:

 Sub accessAll() Dim cell As Range For Each cell In Selection (do something here) Next cell End Sub 

这需要你已经突出显示的每个单元格,并做了一些事情。

非常规或不连续范围具有表示常规矩形子范围的区域。 编辑:请注意,两个领域可能会重叠,所以要小心,如果使用下面的代码…

 Dim a as range, c as range For each a in yourRange.Areas For each c in a 'something with c Next c Next a 

编辑:你可以使用一个函数从你的范围内获得第n个单元格。

请注意,如果您要求索引超出范围的大小,这将返回无。

 'get the n'th cell from a non-contiguous range 'probably not efficient for large ranges... Function NthCell(rng as Range, n as integer) as Range Dim i as integer, c as Range Dim rv as Range i=1 for each c in rng.Cells if i=n then Set rv=c Exit For end if Next c Set NthCell=rv End Function 'Sample usage: Set rng = Range("D1:D6,D12") NthCell(rng, 1).Value = .... NthCell(rng, 7).Value = ....