VBA从excel发送电子邮件(视情况而定)

时间:2016-06-29 07:47:09

标签: excel vba excel-vba email

我是一个绝对的初学者,并试图在同事的日常工作中为一些任务提供便利。我想创建一个代码,用于发送包含excel文件信息的提醒邮件。我们的想法是,Excel应检查第12行中的每个相关行,并检查是否存在" x"写在一列,标记我要发送提醒的行。 使用下面的代码我可以生成所有的电子邮件,但是我有困难在哪里以及如何包括检查if(' If Cells(s,6).Value =" x"然后&#39 ;)以便Excel继续填写所有已填写的行。

非常感谢你的帮助!

 
Sub SendReminderMail() 
  Dim s As Long
  Dim OutLookApp As Object
  Dim OutLookMailItem As Object
  Dim iCounter As Integer
  Dim MailDest As String

  If MsgBox("Are you sure?", vbYesNo) = vbNo Then Exit Sub

  Set OutLookApp = CreateObject("Outlook.application")
  Set OutLookMailItem = OutLookApp.CreateItem(0)

  s = 12

  Do Until Trim$(Cells(s, 1).Value) = ""

    Set OutLookMailItem = OutLookApp.CreateItem(0)
    With OutLookMailItem
      .To = Cells(s, 5).Value
      .Subject = "Reminder: " & Cells(1, 7).Value
      .Body = "Text, " & vbCrLf & vbCrLf & "Text'" & Cells(s, 2).Value 
      s = s + 1
      .Display
    End With
  Loop
End Sub

1 个答案:

答案 0 :(得分:1)

由于您使用Do...Loop检查每一行,因此您需要检查该循环内的if。我已将增量移至s之外的If,以便无论您是否创建邮件项,都会发生这种情况。否则,如果有要发送的邮件项目,您只会更改行,这意味着您将在没有“x”的行上停滞。

Sub SendReminderMail() 
    Dim s As Long
    Dim OutLookApp As Object
    Dim OutLookMailItem As Object
    Dim iCounter As Integer
    Dim MailDest As String

    If MsgBox("Are you sure?", vbYesNo) = vbNo Then Exit Sub

    Set OutLookApp = CreateObject("Outlook.application")
    Set OutLookMailItem = OutLookApp.CreateItem(0)

    s = 12

    Do Until Trim$(Cells(s, 1).Value) = ""
      If Cells(s,6).Value = "x" Then
          Set OutLookMailItem = OutLookApp.CreateItem(0)
          With OutLookMailItem
              .To = Cells(s, 5).Value
              .Subject = "Reminder: " & Cells(1, 7).Value
              .Body = "Text, " & vbCrLf & vbCrLf & "Text'" & Cells(s, 2).Value 
              .Display
          End With
      End If
      s = s + 1
    Loop
End Sub