通过检查复选框中的值发送电子邮件

Send e-mail by check values in checkboxes

我想选中用户窗体中的所有复选框。每个复选框的编号从 2 到 15。选中复选框后,它将从 Excel 个单元格发送电子邮件。

例如Checkbox2 从 sheet

中的 A2 读取数据

我试着做循环。

Sub MailExcelVbaOutlookDisplay()
    Dim zm1 As Variant
    Dim ctl As Control
    Dim i As Variant
    For i = 2 To 15
        Set ctl = Me.Controls("CheckBox" & i)
        If ctl.Visible = True Then
            zm1 = i
            Dim kola As Variant
            kola = Sheets("DataBase").Range("A" & zm1.Value).Value
            Dim kolb As Variant
            kolb = Sheets("Database2").Range("B" & zm1.Value).Value
            Dim OutApp As Object
            Dim OutMail As Object
            Set OutApp = CreateObject("Outlook.Application")
            Set OutMail = OutApp.CreateItem(0)
            With OutMail
                .To = kolb
                .CC = ""
                .Subject = "subject"
                .HTMLBody = "body"
                .Attachments.Add Attachment_Box.Value
                .Display
            End With
            Set OutMail = Nothing
            Set OutApp = Nothing
         End If
    Next i
    Unload Me
End Sub

我假设表单上有 14 个复选框(CheckBox2 到 CheckBox15)。我不太明白 A2 和 CheckBox2 之间的 link ...但我假设 A2 保存是否选中复选框的布尔值;在这种情况下,您不需要引用它,因为您直接引用了 CheckBox。所以......你的代码的这个清理版本将生成电子邮件:

Sub MailExcelVbaOutlookDisplay()
    
    Dim CheckBoxControl As Control
    Dim Counter As Integer
    Dim ToRecipient As String
    Dim OutApp As Object
    Dim OutMail As Object
    
    Set OutApp = CreateObject("Outlook.Application")
    
    For Counter = 2 To 15
        Set CheckBoxControl = Me.Controls("CheckBox" & Counter)
        If CheckBoxControl.Value = True Then
            ToRecipient = Sheets("Database2").Range("B" & Counter).Value
            Set OutMail = OutApp.createitem(0)
            With OutMail
                .To = ToRecipient
                .CC = ""
                .Subject = "subject " & Counter
                .HTMLBody = "body"
                .Attachments.Add Attachment_box.Value
                .Send
            End With
        End If
    Next

    Unload Me
    
End Sub