Excel VBA - 验证是否已选中复选框并连接相应的文本框的值

时间:2016-12-28 00:33:48

标签: excel vba excel-vba email checkbox

我是Excel VBA的初学者,请帮忙。

在客户注册用户表单中,我有一个“联系人”部分,该部分将被保留以接收最多5个正在注册的客户的联系电子邮件。在此userform中,我有以下对象:

  • 5个文本框(txtEmail1txtEmail2txtEmail3,...)
  • 5个复选框(ckboxEmail1ckboxEmail2ckboxEmail3,...)
  • 1 commandbutton(bSendEmail

电子邮件将在文本框中输入,该按钮将用于打开Outlook应用程序,电子邮件已在“收件人”字段中。复选框将用于定义哪些电子邮件将包含在“收件人”字段中。

这是我的怀疑。如何验证选中哪个复选框,仅使用(连接)来自文本框的电子邮件?

实践例1:

TxtEmail1.value = email1@example.com
TxtEmail2.value = email2@example.com
TxtEmail3.value = empty
TxtEMail4.value = email4@example.com
TxtEMail5.value = empty

CkboxEmail1.value = true
CkboxEmail2.value = true
CkboxEmail3.value = false
CkboxEmail4.value = true
CkboxEmail5.value = false

当我按下按钮时,必须将以下数组传递给“.To”属性:

.To = "email1@example.com;email2@example.com;email4@example.com"

实际例子2:

TxtEmail1.value = email1@example.com
TxtEmail2.value = email2@example.com
TxtEmail3.value = empty
TxtEMail4.value = email4@example.com
TxtEMail5.value = empty

CkboxEmail1.value = false
CkboxEmail2.value = false
CkboxEmail3.value = false
CkboxEmail4.value = true
CkboxEmail5.value = false

当我按下按钮时,只有第4封电子邮件会被传递到“.To”属性,因为只有其复选框为真:

.To = "email4@example.com"

Bellow是我用来在bSendEmail Click事件中打开Outlook Application的代码。

Private Sub bSendEmail_Click()

Dim outlookApp       As Object
Dim outlookMail      As Object

On Error GoTo error_outlook
Set outlookApp = CreateObject("Outlook.Application")
Set outlookMail = outlookApp.CreateItem(0)
On Error GoTo 0

On Error Resume Next
With outlookMail
    .To = ""
    .CC = ""
    .BCC = ""
    .Subject = ""
    .Body = ""
    .Importance = 2
    .Display
End With
On Error GoTo 0

Set outlookMail = Nothing
Set outlookApp = Nothing

Exit Sub

error_outlook:

    MsgBox("some message here...", vbOKOnly + vbExclamation, "ERROR - Outlook")
    Exit Sub

End Sub

提前致谢并抱歉英语不好,不是我的母语。

1 个答案:

答案 0 :(得分:1)

更改

.To = ""

Dim TempTo As String
TempTo = ""
If CkboxEmail1 Then TempTo = TempTo & TxtEmail1.value & ";"
If CkboxEmail2 Then TempTo = TempTo & TxtEmail2.value & ";"
If CkboxEmail3 Then TempTo = TempTo & TxtEmail3.value & ";"
If CkboxEmail4 Then TempTo = TempTo & TxtEmail4.value & ";"
If CkboxEmail5 Then TempTo = TempTo & TxtEmail5.value & ";"

之后可能会添加一些额外的代码,以防止没有检查CkBox的问题:

If Len(TempTo) = 0 Then
    MsgBox "No email addresses selected"
    Exit Sub
End If

最后:

.To = TempTo