重新澄清:我是一个优秀的vba新手,所以请耐心等待…
我需要访问非连续范围变量中的单个单元格并更改其值。
是否没有顺序的方式循环通过一个不连续的范围变量?
例如:
rng = Range("d1:d6, d12")
这个范围内有7个单元格,但我无法循环浏览这个范围内的单元格,因为"单元格"函数将第7个单元格视为d7。或者我可以用其他方式吗?
我不能使用FOR EACH,因为我需要使用除范围本身之外的另一个变量来跳过范围并更改其中的值。
这里有一个我想要做的不起作用的例子:
' 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)
我不想使用数组,因为我不只是想单独操作单元格的值,我想改变单元格中的值,并将其反映在该单元格中,而不必经历将数组内容重新加载到范围中的过程,这无论如何都会再次给我带来同样的问题。
有什么建议吗?
嗯,这个怎么样?
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
这会获取您高亮显示的每个单元格并对其执行某些操作。
非规则或非连续范围具有代表规则矩形子范围的Areas
。编辑:注意两个区域可能重叠,所以如果使用下面的代码,请注意这一点。。。
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个单元格。
请注意,如果您要求的索引超出范围大小,则此操作将返回Nothing。
'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 = ....