VBA - 多个动态范围的相同格式

时间:2016-10-08 00:39:12

标签: excel vba excel-vba

我希望以相同的模式格式化2列中的数据。每个数据列的长度基于结果数组的上边界。我最初将它们分别格式化并且按预期工作,但我希望尽可能保持代码的精确度。

我尝试了下面的代码,但它创建了从第1范围到第2范围的范围,而不是匹配这些范围的总和:

With statsWS
    With Range(.Range("b2:c" & UBound(vGoals) + 1), _
               .Range("e2:f" & UBound(vAssists) + 1))
        With .Borders
            .LineStyle = xlContinuous
            .Color = rgbGrey
        End With
    End With
End With

3 个答案:

答案 0 :(得分:2)

类似的东西:

With statsWS.Range("b2:c" & (UBound(vGoals) + 1) & ",e2:f" & (UBound(vAssists) + 1)).Borders
    .LineStyle = xlContinuous
    .Color = rgbGrey
End With

答案 1 :(得分:1)

你可以使用Chris Neilsen的建议:

With statsWS
    With Union(.Range("B2:C" & UBound(vGoals) + 1), .Range("E2:F" & UBound(vAssists) + 1))
        With .Borders
            .LineStyle = xlContinuous
            .Color = rgbGrey
        End With
    End With
End With

但是如果你想保持你的代码精益,那么你可以将范围传递给另一个子程序来处理格式。将业务逻辑与显示分开:

用法:

ApplyBorders .Range("B2:C" & UBound(vGoals) + 1), .Range("E2:F" & Bound(vAssists) + 1)

代码:

Sub ApplyBorders(ParamArray Ranges())
    Dim x As Long
    Dim r As Range
    Set r = Ranges(0)

    For x = 1 To UBound(Ranges())
        Set r = Union(r, Ranges(x))
    Next

    With r.Borders
        .LineStyle = xlContinuous
        .Color = rgbGrey
    End With
End Sub

注意:因为ApplyStandardBorders使用ParamArray,您可以将0到60个参数传递给它(Excel 2003中只有29个)。

答案 2 :(得分:1)

您还可以使用Range("Address1,Address2")方法获得不同范围的并集

With statsWS
    With .Range(.Range("b2:c" & UBound(vGoals) + 1).Address & "," & .Range("e2:f" & UBound(vAssists) + 1).Address).Borders
        .LineStyle = xlContinuous
        .Color = rgbGrey
    End With
End With