构建备用小区范围vba

时间:2013-11-29 16:36:44

标签: excel vba dynamic range alternate

我建立动态备用细胞范围的意图是失败的,显然是因为缺乏知识。

For j = 1 To numFrame
    Set MaxStRange_OD_OUT = ActiveSheet.Range(Cells(1, 2 * (j + 1)))
    MaxVal = Application.Max(MaxStRange_OD_OUT)
    Debug.Print MaxVal
Next j

我希望得到的是

MaxStRange_OD_OUT = ActiveSheet.Range(Cells(1, 4),Cells(1, 6),Cells(1, 8))

当然,单元格的数量可以改变,比如从1到10(numFrame)

感谢

2 个答案:

答案 0 :(得分:1)

您可以使用Application.Union来构建范围。

Sub UnionRangeExample()

Dim rng As Range
Dim i As Long

    For i = 1 To 20 Step 2

    If rng Is Nothing Then

    Set rng = ActiveSheet.Cells(i, 1)

    Else

    Set rng = Application.Union(rng, ActiveSheet.Cells(i, 1))
    End If

    Next i

MsgBox rng.Address

End Sub

在您的情况下,您可以像这样使用它:

Sub UnionRangeExample_v2()

Dim rng As Range
Dim j As Long
Dim numFrame As Long


numFrame = 10


    For j = 1 To numFrame
        If rng Is Nothing Then

        Set rng = ActiveSheet.Cells(1, 2 * (j + 1))

        Else

        Set rng = Application.Union(rng, ActiveSheet.Cells(1, 2 * (j + 1)))
        End If
    Next j

MsgBox "max for: " & rng.Address & " is " & Application.Max(rng)

End Sub

答案 1 :(得分:1)

您可以在此处试用此代码

Function MyMaxValue() as Double
    Dim maxValue As Double, numFrame As Double, i As Integer, currentValue As Double

    numFrame = 7

    For i = 1 To numFrame
        currentValue = Cells(1, 2 * (j + 1)).value
        If currentValue > maxValue Then
            maxValue = currentValue
            Debug.Print "new value = " & maxValue
        End If
    Next i

    MyMaxValue = maxValue    
End Function