仅当保存工作簿时,才根据单元格中的值发送电子邮件

时间:2018-10-31 13:42:50

标签: excel vba excel-vba

我有一个单元格B8,检查该单元格是否当天已输入数据,并根据计数输出一个数字。它会检查是否有空白条目,显然在开始填写工作表时,当天的所有单元格都将是空白的,我希望它仅在保存工作表后才执行检查。

我成功管理给科学怪人的代码会在条件满足时立即准备一封电子邮件,我不确定如何更改它以适应我的需求。

Sub Mail_with_outlook()
Dim OutApp As Object
Dim OutMail As Object
Dim emlto As String, emlcc As String, emlbcc As String
Dim emlsub As String, emlbody As String

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

emlto = "email@abc.def"
emlcc = ""
emlbcc = ""
emlsub = "Raw Material Projection"
emlbody = "Good Day" & vbNewLine & vbNewLine & _
          "There might be an issue with the data inputed in today's sheet"


With OutMail
    .To = emlto
    .CC = emlcc
    .BCC = emlbcc
    .Subject = emlsub
    .Body = emlbody
    .Display    '  use .Send once tested
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub





Private Sub Worksheet_Calculate()
Dim FormulaRange As Range
Dim NotSentMsg As String
Dim MyMsg As String
Dim SentMsg As String
Dim MyLimit As Double

NotSentMsg = "Not Sent"
SentMsg = "Sent"

'Above the MyLimit value it will run the macro
MyLimit = 10

'range with the Formula that I want to check
Set FormulaRange = Me.Range("B8")

On Error GoTo EndMacro:
For Each FormulaCell In FormulaRange.Cells
    With FormulaCell
        If IsNumeric(.Value) = False Then
            MyMsg = "Not numeric"
        Else
            If .Value > MyLimit Then
                MyMsg = SentMsg
                If .Offset(0, 1).Value = NotSentMsg Then
                    Call Mail_with_outlook
                End If
            Else
                MyMsg = NotSentMsg
            End If
        End If
        Application.EnableEvents = False
        .Offset(0, 1).Value = MyMsg
        Application.EnableEvents = True
    End With
Next FormulaCell

ExitMacro:
Exit Sub

EndMacro:
Application.EnableEvents = True

MsgBox "Some Error occurred." _
     & vbLf & Err.Number _
     & vbLf & Err.Description

End Sub

1 个答案:

答案 0 :(得分:4)

我会将您的逻辑放在BeforeSave事件中。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
   'your logic goes here
End Sub

如果仅检查范围内是否有东西,而在此之前它完全为空,请考虑使用COUNTA/COUNT函数。

注意:

  

在保存工作簿之前发生。

     

语法表达。 BeforeSave( SaveAsUI 取消

     

expression一个表示Workbook对象的变量。

     

参数

     

SaveAsUI:必填,布尔值,描述:如果“另存为”对话框为   由于所做的更改需要保存在工作簿中,因此显示。

     

取消:必需,布尔值,描述:事件发生时为False。如果事件   过程将此参数设置为True,但在以下情况下不会保存工作簿   该过程完成。