使用VBA“With”语句来引用对象本身?

PG_*_*345 5 excel vba

如果我在 VBA 中使用“With”关键字,则必须访问“With”锁定的对象中的属性/方法。但是,我可以在“With”语句中引用对象本身吗?

Fe,假设我有一个函数接受一个范围作为输入。我还将“With”锁定在特定范围内,以便编辑该范围内的多个属性:

Function ViewCellColor(inputrange As Range)
    ' This function takes a range as input
    MsgBox inputrange.Interior.Color
End Function

Sub Test()
    With Range("A1")
        .Select
        .Interior.Color = vbRed
        .Value = 10
        .Font.Bold = True
        Run ViewCellColor(Range("A1")) ' Use range as input to function
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

在这里,我想将范围本身传递给函数,但我必须重写范围引用(A1)以用于函数参数传递。是否可以避免在此处重复输入范围引用?

Mat*_*don 5

你不能,除非对象公开一个返回自身的成员。

Public Property Get Self() As WhateverThatClassIs
    Set Self = Me
End Property
Run Code Online (Sandbox Code Playgroud)

在 的情况下Excel.Range,该Cells属性应该起作用:

With ActiveSheet.Range("A1") '<~ always qualify Range with the sheet you're working with
    .Interior.Color = vbRed
    .Value = 10
    .Font.Bold = True
    ViewCellColor .Cells
End With
Run Code Online (Sandbox Code Playgroud)

请注意,该Range.Cells属性没有任何参数 - 当我们这样做时someRange.Cells(x),下标将与该属性返回的对象的隐藏成员(x)相反。Range.[_Default]RangeCells

因为它不返回任何内容,ViewCellColor所以应该是一个Sub过程,并且inputRange应该传递它的参数ByVal(隐式且不幸的隐式默认值是ByRef),因为该作用域没有业务重新分配该特定Range引用。


或者,您可以声明并分配一个局部Range变量,并使用它来限定重复的成员调用:

Dim Cell As Range
Set Cell = ActiveSheet.Range("A1")

Cell.Interior.Color = vbRed
Cell.Value = 10
Cell.Font.Bold = True

ViewCellColor Cell
Run Code Online (Sandbox Code Playgroud)

与块一样With,它比为每个单独的指令取消引用 aRange好得多ActiveSheet

如果您在表达式中引用该变量,您还可以跳过一些按键With

Dim Cell As Range
Set Cell = ActiveSheet.Range("A1")

With Cell
    .Interior.Color = vbRed
    .Value = 10
    .Font.Bold = True
End With

ViewCellColor Cell
Run Code Online (Sandbox Code Playgroud)

注意:编程主要是阅读代码;在编写代码时花费这几个额外的击键最终很容易得到回报。避免嵌套块,并保持它们很小 - 当出现问题时,它们可能会巧妙地使问题复杂化:例如,With您通常不希望在错误处理中意外地重新输入带有语句的块WithResume