“With”语句中的子例程
考虑下面的例子
Private Sub drawBorders(listOfBorders) For Each Item In listOfBorders With .Borders(Item) .LineStyle = xlContinious .ColorIndex = xlAutomatic .Weight = xlThin End With Next Item End Sub Sub main() Dim TopBottom() as Variant Dim myRange As Range TopBottom = Array(xlEdgeTop, xlEdgeBottom) myRange = Range("A1") With myRange .value = a Call DrawBorders(topBottom) End With End Sub
我有一个With
语句序列,其中一些代码是相当重复的。
我在DrawBorders
子文件中得到一个错误:
无效或不合格的参考
是否有可能从With
语句导入Sub
的引用?
您应该始终在您的Sub或Function中指定参数的types。
您得到的DrawBorders
的错误是因为With .Borders(Item)
没有任何对象被引用到(没有With Object
之前)。
我的猜测是你想在你的调用中传递引用,这就是为什么你需要传递一个对象,因为当你调用一个函数或子函数时,来自主代码的With
不会跟随!
这是我对你的代码的build议:
Private Sub DrawBorders(ListOfBorders As Variant, RangeToFormat As Range) For Each Item In ListOfBorders With RangeToFormat.Borders(Item) .LineStyle = xlContinuous .ColorIndex = xlAutomatic .Weight = xlThin End With Next Item End Sub Sub main() Dim TopBottom() As Variant, _ Ws As Worksheet, _ MyRange As Range Set Ws = ActiveSheet Set MyRange = Ws.Range("A1:J10") MyRange.Value = A TopBottom = Array(xlEdgeTop, xlEdgeBottom) With Ws Call DrawBorders(TopBottom, .Range("A1:J10")) End With '----Or 'Call DrawBorders(TopBottom, MyRange) End Sub
这应该工作
Private Sub DrawBorders(listOfBorders() as Variant, r As Range) For Each Item In listOfBorders With r.Borders(Item) .LineStyle = xlContinuous .ColorIndex = xlAutomatic .Weight = xlThin End With Next Item End Sub Dim TopBottom() As Variant Dim myRange As Range TopBottom = Array(xlEdgeTop, xlEdgeBottom) myRange = Range("A1") With myRange .Value = a End With Call DrawBorders(TopBottom, myRange)