iDevlop
iDevlop

Reputation: 25272

VBA call class property from the class

In a VBA class module (let's say in Excel or Access), I wrote a function SomeFunction() returning a value.
If I call this from another function/sub in the class, should I call it:
a) this way: myVar = SomeFunction or
b) this way: myVar = Me.SomeFunction ?

I think both work, so except for the writing style and clarifying SomeFunction is part of the class, does it make any difference?

Upvotes: 5

Views: 1567

Answers (2)

Erik A
Erik A

Reputation: 32682

Both are indeed valid, but way B should be preferred since it's more explicit what you're doing.

Consider the following (valid) class code:

Public Property Get SomeValue() As Integer
    SomeValue = 5
End Property

Public Property Get AnotherValue() As Integer
    Dim SomeValue As Integer
    SomeValue = 3
    AnotherValue = SomeValue 'Returns 3
    Debug.Print Me.SomeValue 'Returns 5
End Property

Because you can (but shouldn't) do this in VBA, it's a good practice to use Me. to make it clear you're using a class property and not a variable.

Upvotes: 6

Vityata
Vityata

Reputation: 43593

As far as I know - It does not make any difference.

However, if you use Me. in the class, you can use the Intellisense to see the available subs, functions and properties, which could be a bit handy:

enter image description here

However, I prefer not to use the Me.


If you are having the following in a module:

Public Function Foo()
    Foo = 5
End Function

Sub TestMe()
    Dim cls As New Klasse1
    cls.TestMe
End Sub

And then the following in Klasse1:

Sub TestMe()
    Debug.Print Modul1.Foo
    Debug.Print Me.Foo
    Debug.Print Foo
End Sub

Function Foo()
    Foo = 10
End Function

it is visible that the existense of Me. is just syntax sugar.

Upvotes: 3

Related Questions