重新获得:我是一名优秀的新手,所以请耐心等待......
我需要访问非连续范围变量中的单个单元格并更改其值。
是否没有顺序的方法来遍历非连续的范围变量?
例如:
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)
我不想使用数组,因为我不想单独操作单元格的值,我想改变单元格中的值并将其反映在该单元格中而无需经过将数组内容重新加载到范围内的过程,无论如何都会给我带来同样的问题。
有什么建议吗?
答案 0 :(得分:1)
如果您在电子表格中突出显示要访问的单元格,则可以执行以下操作:
Sub accessAll()
Dim cell As Range
For Each cell In Selection
(do something here)
Next cell
End Sub
这会占用您突出显示的每个单元格并对其执行某些操作。
答案 1 :(得分: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
答案 2 :(得分:0)
非常规或非连续范围的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 = ....