George Skelton
George Skelton

Reputation: 1125

VBA "With object" syntax - can you refer to the object itself?

I often use the With object syntax when I'm doing a bunch of different stuff with an object. It's useful shorthand for calling the object's properties/methods without having to clutter up the code reusing the object's name. However sometimes I want to call a function which takes as an argument the object itself. Is there any way to refer to the object in that case?

' Class Module
' Class1

' Code Module
Sub f(byref obj as Class1)
End Sub

Sub test()
  Dim obj as Class1: set obj = new Class1
  With obj
    f Me ' Doesn't work - can you refer to obj in this context?
    f obj ' Works but I don't like it when the object has a long name
  End With
End Sub

Upvotes: 5

Views: 1268

Answers (2)

Phil
Phil

Reputation: 11

I realize this is an old posting but I thought this might help others that search for a solution. Actually, there is a slight workaround for this that I have used. It isn't as nice as having something like "Me" (that doesn't work here) but it can help.

You can use the set statement to assign the object to a temporary variable that you can use inside the With statement as in the following example (using your original example above):

set s= obj with s f s end with

The variable s can be any shorter name you wish since it acts like a variable. When you have a large object specification in place of obj, this comes in handy. Hope this helps someone.

Upvotes: 1

rory.ap
rory.ap

Reputation: 35270

No, there is not. You just have to use the object itself, as you have done in your code.

Upvotes: 3

Related Questions