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

VBA-多个动态范围的格式相同,vba,excel,Vba,Excel,我想以相同的模式格式化两列中的数据。每个数据列都有其基于结果数组上边界的长度。我最初分别格式化了这两个代码,并按预期工作,但我希望代码尽可能精简 我尝试了下面的代码,但它创建了从第一个范围到第二个范围的范围,而不是匹配这些范围的总和: With statsWS With Range(.Range("b2:c" & UBound(vGoals) + 1), _ .Range("e2:f" & UBound(vAssists) + 1))

我想以相同的模式格式化两列中的数据。每个数据列都有其基于结果数组上边界的长度。我最初分别格式化了这两个代码,并按预期工作,但我希望代码尽可能精简

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

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
大概是这样的:

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

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

你可以使用克里斯·尼尔森的建议:

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(vassits)+1)

代码:
注意:由于ApplyStandardBorders使用ParamArray,您可以向其传递0到60个参数(在Excel 2003中仅为29个)。

您可以使用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(vassits)+1)

代码:
注意:由于ApplyStandardBorders使用ParamArray,因此您可以向其传递0到60个参数(在Excel 2003中仅为29个)。

您还可以使用
范围(“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

您还可以使用
范围(“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

使用Application.UnionUse Application.Union您知道在这些范围内循环并对每个范围应用格式是否比使用Union或上述其他方法并仅应用一次效率低?只有两个范围,您不会注意到差异。我更新了我的答案,使之符合范围。如果您使用内置样式或自定义样式,工作簿的性能会更好。您知道在这些范围内循环并为每个范围应用格式是否比使用Union或上述其他方法并仅应用一次效率低?仅使用两个范围,您不会注意到差异。我更新了我的答案,使之符合范围。如果您使用内置样式或自定义样式,您的工作簿的性能会更好。@RyszardJędraszyk,您完成了吗?@RyszardJędraszyk,您完成了吗?