0

重新声明:我是一个 excel 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)

我不想使用数组,因为我不想单独操作单元格的值,我想更改单元格中的值并将其反映在该单元格中,而不必经历重新加载的过程数组内容进入范围,无论如何这再次给我带来了同样的问题。

有什么建议么?

4

3 回答 3

1

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

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

这将获取您突出显示的每个单元格并对其执行某些操作。

于 2012-07-21T15:48:12.420 回答
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
于 2012-07-21T18:40:14.600 回答
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 = ....
于 2012-07-21T16:12:12.270 回答