繁体   English   中英

“带有”语句中的子例程

[英]Subroutine within a 'With' statement

考虑以下说明性示例

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

这应该工作

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)

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

您得到的DrawBorders的错误是由于DrawBorders With .Borders(Item) ,它没有任何要引用的With Object之前没有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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM