gpt4 book ai didi

excel - 使用 VBA "With"语句来引用对象本身?

转载 作者:行者123 更新时间:2023-12-04 10:11:11 24 4
gpt4 key购买 nike

如果我在 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)。是否可以避免在此处重复输入范围引用?

最佳答案

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

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

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
Run ViewCellColor .Cells
End With

请注意 Range.Cells属性没有任何参数 - 当我们使用 someRange.Cells(x) , (x)下标违背隐藏 Range.[_Default] Range 的成员 Cells 返回的对象属性(property)。

因为它没有返回任何东西, ViewCellColor应该是 Sub程序及其 inputRange应传递参数 ByVal (隐含和不幸的隐含默认值是 ByRef )因为该范围没有业务重新分配该特定 Range引用。

关于excel - 使用 VBA "With"语句来引用对象本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61325861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com