Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Mismatch when passing reference to UserForm instance with 'Me'

Tags:

vba

Consider the following code in a VBA module called Module1:

Sub StartTest()
    Dim frm As UserForm1
    Set frm = New UserForm1
    frm.Show
End Sub

Sub Notify(fromForm As UserForm1)
    MsgBox "Notified."
End Sub

And the following code in UserForm1:

Private Sub CommandButton1_Click()
    Module1.Notify (Me)
End Sub

When I run StartTest the form appears, and when I click the button, I'm getting a "Type mismatch" error on Module1.Notify (Me) in the CommandButton1_Click() sub. Why?

If I change Module1.Notify (Me) to Call Module1.Notify(Me) (thanks @sous2817 for pointing this out) or to Module1.Notify Me, then I don't get the error. So why does it happen when I use Module1.Notify (Me)?

like image 950
rory.ap Avatar asked Apr 02 '26 13:04

rory.ap


1 Answers

Change your button code to this:

Private Sub CommandButton1_Click()
    Call Module1.Notify(Me)
End Sub

Seems to give the expected results on my end...

As for the "why", reference here: http://msdn.microsoft.com/en-us/library/wcx04ck5(VS.85).aspx

Specifically:

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

I don't think you can get more of an authoritative explanation than this: http://blogs.msdn.com/b/ericlippert/archive/2003/09/15/52996.aspx

like image 126
sous2817 Avatar answered Apr 04 '26 05:04

sous2817