公开发行时自动运行

时间:2018-01-16 16:56:55

标签: vba excel-vba autorun email-notifications excel

首先,我在VBA编程方面不是很精明。我过去在Java,C ++,C#和其他一些程序中做了很多编程,因此我对编程并不是全新的。

我目前的问题是我有一个库存清单,我希望一旦某个数量达到某个值,就会通过电子邮件发送通知。电子邮件通知已设置并正常工作,除非工作表已关闭然后重新打开,如果值未超过先前设置的值,则会再次发送通知。例如,如果数量等于或低于1,则会通过电子邮件发送通知。如果在保存和关闭工作表之前该数量未更改为2+,则下次打开工作表时,将再次发送通知。

我想限制这一点,以便只有在第一次更改数量时才会发送通知。

以下代码:

Public Function EmailNotification(model As String, color As String, cell1 As Range)
    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range


    Application.ScreenUpdating = False
    Set OutApp = CreateObject("Outlook.Application")

    On Error GoTo cleanup

        If cell1.Value <= 1 Then

            'For Each cell In Columns("R").Cells.SpecialCells(xlCellTypeConstants)
                'If cell.Value Like "?*@?*.?*" And _
                    'LCase(Cells(cell.Row, "S").Value) = "yes" Then

                       Set OutMail = OutApp.CreateItem(0)
                       On Error Resume Next
                       With OutMail
                           .To = "username@domain.com"
                           .Subject = "Excel Notification: Toner Renewal"
                           .Body = "Dear Team," & _
                               vbNewLine & vbNewLine & _
                               "Please prep an order for " & color & " toner for a Dell " & model & vbNewLine & vbNewLine & _
                               "Quantity Remaining: " & cell1 & vbNewLine & vbNewLine & _
                               "Notification Sent: " & Now() & " from " & ActiveWorkbook.FullName


                           .Send
                       End With
                       On Error GoTo 0
                       Set OutMail = Nothing
                   'End If
               'Next cell

        End If

cleanup:
    Set OutApp = Nothing
    Application.ScreenUpdating = True
End Function

cell1是在函数中检查的数量。

我不确定是否有办法在启动时暂停此AutoRun,然后只要其中一个数量发生更改,就允许它再次运行。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我在你的工作簿中取一个单元格(比如cell2)并存储一个布尔值来说明电子邮件是否已经发送过一次。

你的功能看起来像这样:

Public Function EmailNotification(model As String, color As String, cell1 As Range, cell2 As Range)

  Dim notifSent As Boolean: notifSent = cell2.Value '<-- get the value of cell2
  If cell1.Value <= 1 And Not notifSent 'if quantity below threshold and no notification yet sent
      'you send the email for the first time...
      cell2.Value = True 'and you set this information in your cell
  ElseIf cell1.Value > 1 And notifSent 'if quantity above threshold and notification has been sent before
      cell2.Value = False 'reset notification to false
  End If