使用'中的子程序。声明

时间:2015-11-12 12:28:10

标签: excel vba excel-vba

考虑以下说明性示例

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 sub:

收到错误
  

无效或不合格的参考

是否可以将With语句中的引用导入Sub

2 个答案:

答案 0 :(得分:2)

这应该有效

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)

答案 1 :(得分:2)

您应该始终在Sub或Function中指定参数的类型。

您获得的DrawBorders错误是由于此With .Borders(Item)没有引用任何对象(之前没有With Object)。

我的猜测是你想在调用中传递引用,这就是你需要传递一个对象的原因,因为当你调用一个函数时,主代码中的With不会出现或者分!

以下是我的代码命题:

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
相关问题