如何在多个范围内调用函数

时间:2019-05-24 14:44:46

标签: excel vba

我有一个格式化范围的函数,但它似乎只是格式化我选择的第一个范围。

我尝试先选择范围然后进行格式化,但这会延长我的代码很多时间。

Sub Numbers()

    Call format(Range(Cells(4, "A"), Cells(2 + i - j, "AA")))

    Call format(Range(Cells(4, "C"), Cells(4 + i - j, "F")))

    Call format(Range(Cells(4, "G"), Cells(4 + i - j, "J")))

End Sub

Sub format(R As Range)

    With R
        Selection.Borders(xlDiagonalDown).LineStyle = xlNone
        Selection.Borders(xlDiagonalUp).LineStyle = xlNone
        With Selection.Borders(xlEdgeLeft)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .TintAndShade = 0
            .weight = xlMedium
        End With

    End With

End Sub

我想格式化所有范围,但仅格式化第一个范围,即:仅格式化-> Range(Cells(4, "A"), Cells(2 + i - j, "AA"))

1 个答案:

答案 0 :(得分:0)

您可以在主子目录中循环浏览并调用format子目录x次,也可以修改format子目录以使用ParamArray。这样一来,您就可以将任意多个范围传递给format子行

Sub formatRange(ParamArray rngs() As Variant)
    Dim i As Long

    For i = 0 To UBound(rngs)
        If TypeName(rngs(i)) = "Range" Then
            With rngs(i)
                Debug.Print i, .Address, TypeName(rngs(i))

                .Borders(xlDiagonalDown).LineStyle = xlNone
                .Borders(xlDiagonalUp).LineStyle = xlNone
                With .Borders(xlEdgeLeft)
                    .LineStyle = xlContinuous
                    .ColorIndex = 0
                    .TintAndShade = 0
                    .Weight = xlMedium
                End With
            End With
        End If
    Next i
End Sub

Sub test()
    formatRange Range("A1"), Range("A2"), Range("A3")
    formatRange Range("B5"), Range("I6")
    ' etc. etc....
End Sub