1

How can I define a sub or function in VBA?

This is my code:

Private Sub CommandButton1_Click()
    Call Send_Mail
End Sub

In Worksheet "Sheet1" I have a CommandButton called Send_Mail and in "Sheet2" I have also a CommandButton. When I click the CommandButton in Sheet2 I want that the Button in Sheet1 will run.

With my code the : error "Sub or Function is not defined" appears.

EDIT:

Code for Send_Mail:

Public Sub Send_Mail_Click()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim nameList As String
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    On Error GoTo cleanup

    For i = 4 To 22                                                                         
        If Range("B4").Value <> "" Then                                                        
            nameList = nameList & ";" & Range("C" & i).Value
        End If
    Next
        With OutMail
            .To = nameList
            .Subject = "Subject Line"
            .Body = "Body Text"
            .Send
        End With
cleanup:
    Set OutApp = Nothing
    MsgBox "E-Mail sent."
    MsgBox Err.Description
End Sub
3
  • You need to make sure Sub Send_Mail is located in a regular code module, and not a worksheet module, that way it is accessible Commented Apr 25, 2018 at 6:04
  • Can you please show more of your codes? And what do you mean with this one: When I click the CommandButton in Sheet2 I want that the Button in Sheet1 will run, you mean the function assigned to button 1? Commented Apr 25, 2018 at 6:09
  • I went to "Create Macro" paste the code from Send_Mail to it. Saved it as Send_Mail .. but still the same error Commented Apr 25, 2018 at 6:16

1 Answer 1

1

I don't know what the underlying sub procedure attached to the Sheet1 button has been named but it is likely it has a similar name.

'Sheet2's button sub procedure
Private Sub CommandButton1_Click()
    Call Sheet1.CommandButton1_Click
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Or Sheet1.Send_Mail?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.