如何添加输入日期后将自动运行的代码。如果代码包含其他单元格-是否需要首先填充它们。这个想法是输入今天的日期并发送电子邮件。电子邮件代码有效,但我需要代码自动运行。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If IsDate(Range("A1").Value) Then
'MsgBox "Plase enter a date in A1"
'response = MsgBox(msg, vbYesNo)
'If response = vbYes Then
email
Else
End If
'End If
End Sub
Sub email()
Dim r As Range
Dim cell As Range
Set r = Range("A1:S20")
For Each cell In r
If cell.Value = Date Then
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Dim Mail_Object, Mail_Single As Variant
Email_Subject = Cells(cell.Row, "C").Value
Email_Send_From = "Jean@test.com"
Email_Send_To = "Joe@test.com"
Email_Cc = ""
Email_Bcc = ""
Email_Body = "Hi " & Cells(cell.Row, "c").Value _
& vbNewLine & vbNewLine & _
Cells(cell.Row, "D").Value & _
" has been submited"
On Error GoTo debugs
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.cc = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body
.send
End With
End If
Next
Exit Sub
debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub
答案 0 :(得分:0)
我相信这就是您想要的。当A1
中的值更新时,它将首先验证输入是否为日期。如果输入的日期无效,您将收到代码中的第一个MsgBox
。
如果条目 是有效日期,则会询问用户是否要发送电子邮件。如果他们选择No
,则宏将结束。如果他们选择Yes
,则您的Email Sub将开始执行。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Response As String
If Not IsDate(Range("A1").Value) Then
MsgBox "Plase enter a valid date in A1"
Else
Response = MsgBox("Do you want to send email?", vbYesNo)
If Response = vbYes Then Call Email
End If
End Sub
如果您不希望用户选择Yes
或No
来发送电子邮件,而您希望它在A1
中的条目被验证后立即发生作为日期,然后将您的IF语句更改为此:
If Not IsDate(Range("A1").Value) Then
MsgBox "Plase enter a valid date in A1"
Else
Call Email
End If
您还应该更新它,使其仅在更改特定范围(在这种情况下,可能是单个单元格)时执行。否则,当更改任何单元格时,宏将触发。相反,请确定应触发该宏的范围,然后在更改的单元格与您的预定范围重叠(或Intersects
)时调用该宏。