EXCEL VBA - 定义子或函数

时间:2018-04-25 06:01:16

标签: excel vba excel-vba

如何在VBA中定义子或函数?

这是我的代码:

Private Sub CommandButton1_Click()
    Call Send_Mail
End Sub

在工作表“Sheet1”中,我有CommandButton名为 Send_Mail ,在“Sheet2”中我还有一个CommandButton。当我单击Sheet2中的CommandButton时,我希望Sheet1中的Button能够运行。

使用我的代码:出现错误“Sub or Function is defined”。

修改

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

1 个答案:

答案 0 :(得分:1)

我不知道附加到Sheet1按钮的基础子程序的名称是什么,但很可能它的名称相似。

'Sheet2's button sub procedure
Private Sub CommandButton1_Click()
    Call Sheet1.CommandButton1_Click
End Sub