VBA – 多个dynamic范围的相同格式

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

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

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 

你可以使用Chris Neilsen的build议:

 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个参数)。

像这样的东西:

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

您也可以使用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