如何使用Loop with Variable Range

时间:2016-02-16 19:11:43

标签: excel vba excel-vba

在下面的代码中,当我到达Range(i)中的每个curCell时,它无法理解我引用的Range。我收到一个Object'_worksheet'方法'范围'失败了。我知道当前的范围(i)是不正确的,但我已经尝试了每一个变化,似乎没有任何效果。

有人可以帮我理解如何让我的代码识别Range1,然后是Range2等吗?

Sub Worksheet_Change(ByVal Target As Range)

Dim Range1 As Range, Range2 As Range, Range3 As Range, Range4 As Range
Dim curCell As Variant
Dim i As Integer
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets(cCostingQSheet)

Set Range1 = ws.Range("E6:E9")
Set Range2 = ws.Range("E15:E19")
Set Range3 = ws.Range("E21")
Set Range4 = ws.Range("E23")

For i = 1 To 4

    For Each curCell In Range(i).Cells

        If Not WorksheetFunction.IsNumber(curCell) = True Then

            curCell.Value = 0

        Else

        End If

    Next

Next

End Sub

3 个答案:

答案 0 :(得分:5)

如果你想要这样的设置,你需要使用一个数组。方法如下:

替换你的变量声明声明

'Instead of your original
'Dim Range1 As Range, Range2 As Range, Range3 As Range, Range4 As Range

'Use this:
Dim arrRanges(1 To 4) As Range

然后更改设置范围的方式:

Set arrRanges(1) = ws.Range("E6:E9")
Set arrRanges(2) = ws.Range("E15:E19")
Set arrRanges(3) = ws.Range("E21")
Set arrRanges(4) = ws.Range("E23")

当你遍历它们时,它看起来像这样:

        For Each curCell In arrRanges(i).Cells

答案 1 :(得分:4)

您可以为范围变量指定一个非连续范围,而不是使用4个不同的范围变量或范围数组(如@tigeravatar在其优秀答案中所述)。像这样:

Sub test()
    Dim R As Range
    Dim myCell As Range
    Dim ws As Worksheet
    Dim i As Long

    Set ws = ActiveSheet
    Set R = ws.Range("E6:E9,E15:E19,E21,E23")
    i = 1
    For Each myCell In R.Cells
        myCell.Value = i
        i = i + 1
    Next myCell
End Sub

答案 2 :(得分:1)

我会更进一步

  • 查看整个范围内的每个范围。
  • 使用变量数组处理范围(范围区域多于一个单元格),然后转储回范围。

Sub recut()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim lngCol As Long
    Dim lngRow As Long
    Dim ws As Worksheet

    Set ws = ActiveSheet
    Set rng1 = ws.Range("E6:E9,E15:E19,E21,E23")

    For Each rng2 In rng1.Areas
        If rng2.Cells.Count > 1 Then
            x = rng2.Value
            For lngRow = 1 To UBound(x)
                For lngCol = 1 To UBound(x, 2)
                    If IsNumeric(x(lngRow, lngCol)) Then x(lngRow, lngCol) = 0
                Next
            Next
            rng2.Value2 = x
        Else
            If IsNumeric(rng2.Value) Then rng2.Value = 0
        End If
    Next rng2

End Sub