vbafunctionms-accessoffice-2003

Call a VBA Function into a Sub Procedure


I know this is a simple question for someone out there, but I have never really used function module at all because I did not understand what they were.

So I have a whole bunch of things I can use this for (cut down on redundancy), but I want to know how I call into a sub (like a button click) procedure from a form.

I tried this...

Sub Command_Click()
    Call "pptCreator"
End Sub

I know that is pretty bad, but I have no idea how to bring this into a procedure.


Solution

  • Here are some of the different ways you can call things in Microsoft Access:

    To call a form sub or function from a module

    The sub in the form you are calling MUST be public, as in:

    Public Sub DoSomething()
      MsgBox "Foo"
    End Sub
    

    Call the sub like this:

    Call Forms("form1").DoSomething
    

    The form must be open before you make the call.

    To call an event procedure, you should call a public procedure within the form, and call the event procedure within this public procedure.

    To call a subroutine in a module from a form

    Public Sub DoSomethingElse()
      MsgBox "Bar"
    End Sub
    

    ...just call it directly from your event procedure:

    Call DoSomethingElse
    

    To call a subroutine from a form without using an event procedure

    If you want, you can actually bind the function to the form control's event without having to create an event procedure under the control. To do this, you first need a public function in the module instead of a sub, like this:

    Public Function DoSomethingElse()
      MsgBox "Bar"
    End Function
    

    Then, if you have a button on the form, instead of putting [Event Procedure] in the OnClick event of the property window, put this:

    =DoSomethingElse()
    

    When you click the button, it will call the public function in the module.

    To call a function instead of a procedure

    If calling a sub looks like this:

    Call MySub(MyParameter)
    

    Then calling a function looks like this:

    Result=MyFunction(MyFarameter)
    

    where Result is a variable of type returned by the function.

    NOTE: You don't always need the Call keyword. Most of the time, you can just call the sub like this:

    MySub(MyParameter)