Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA call class property from the class

Tags:

vba

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?

like image 503
iDevlop Avatar asked Aug 09 '18 12:08

iDevlop


2 Answers

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.

like image 57
Erik A Avatar answered Nov 09 '22 20:11

Erik A


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.

like image 3
Vityata Avatar answered Nov 09 '22 21:11

Vityata