Home » excel » excel – Use VBA "With" statement to refer to the object itself?

excel – Use VBA "With" statement to refer to the object itself?

Posted by: admin May 14, 2020 Leave a comment

Questions:

If I use the “With” keyword in VBA, I have to access attributes/methods in the objects which “With” is locked on. But, can I refer to the object itself within the “With” statement?

F.e., suppose i have a that function takes a range as input. I also lock “With” on a specific range, for editing multiple attributes in the range:

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

Here, I want to pass the range itself to the function, but I here have to re-write the range reference (A1) for the function argument passing. Is it possible to avoid double-typing the range reference here?

How to&Answers:

You can’t, unless the object exposes a member that returns itself.

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

In the case of Excel.Range, the Cells property should work:

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

Note that the Range.Cells property does not have any parameters – when we do someRange.Cells(x), the (x) subscript goes against the hidden Range.[_Default] member of the Range object that’s returned by the Cells property.

Because it’s not returning anything, ViewCellColor should be a Sub procedure, and its inputRange parameter should be passed ByVal (the implicit and unfortunate implicit default is ByRef) because that scope has no business re-assigning that particular Range reference.