【问题标题】:Use VBA "With" statement to refer to the object itself?使用 VBA 的“With”语句来引用对象本身?
【发布时间】:2020-04-20 15:15:31
【问题描述】:

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

F.e.,假设我有一个函数将范围作为输入。我还将“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

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

【问题讨论】:

  • 不,但您可以使用.Range("A1").Cells(1)
  • 不需要.Select
  • urdearboy:我知道,这只是为了举例。

标签: excel vba


【解决方案1】:

你不能,除非对象暴露了一个返回自身的成员。

Public Property Get Self() As WhateverThatClassIs
    Set Self = Me
End Property

对于Excel.RangeCells 属性应该可以工作:

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

请注意,Range.Cells 属性没有任何参数 - 当我们执行 someRange.Cells(x) 时,(x) 下标与 Range 属性返回的 Range 对象的隐藏 Range.[_Default] 成员相冲突.

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

【讨论】:

  • 好的,但是如果我将使用其他数据对象类型,则无法在“With”中进行引用以对应于 f.e. 中的“Me”。 VBA:s事件处理技术?即,针对“当前”对象本身,而不是其属性?
  • Me 只是本地的(请参阅我的用户配置文件),“当前对象”的概念在本地范围之外不存在 =) ...如果接口没有公开它, ...那么你需要一个局部变量。 With 被高估了。只需拼出局部变量!
猜你喜欢
  • 1970-01-01
  • 2012-05-01
  • 2012-07-15
  • 2013-06-03
  • 1970-01-01
  • 2011-10-29
  • 2018-04-19
  • 2018-12-06
  • 1970-01-01
相关资源
最近更新 更多