代码不检查空string
我不确定为什么我的代码不输出我的消息,即使我的电子表格有一个空的字段。 如果我的消息框中的值显示为空,所以不知道为什么它不是在IsEmpty函数中拾取它。
Sub Button1_Click() Dim Cell As Range Dim name As Range Dim objDate As Date Dim myName As String For Each Cell In Range("P3:P4").Cells myName = Cell.Offset(0, -14).Value If Not IsDate(Cell.Value) Then MsgBox "Please make sure all dates are in a valid form: DD.MM.YYYY" ElseIf Cell.Value <= Date + 30 Then **ElseIf IsEmpty(myName) Then MsgBox "Please enter a name"** Else Dim appOutlook As Outlook.Application Dim mitOutlookMsg As Outlook.MailItem Dim recOutlookRecip As Outlook.Recipient ' Step 1: Initialize an Outlook session. Set appOutlook = CreateObject("Outlook.Application") ' Step 2: Create a new message. Set mitOutlookMsg = appOutlook.CreateItem(olMailItem) With mitOutlookMsg ' Step3: Add the To recipient(s) to message. Set recOutlookRecip = .Recipients.Add(myName) recOutlookRecip.Type = olTo 'Set valid properties like Subject, Body, and Importance of the message. .Subject = "Test123" '.Body = "Test" .BodyFormat = olFormatHTML .HTMLBody = "Dear " & myName & " TEST EMAIL " .Importance = olImportanceHigh 'High importance ' Resolve every Recipient's name For Each recOutlookRecip In .Recipients recOutlookRecip.Resolve If Not recOutlookRecip.Resolve Then mitOutlookMsg.Display End If Next .Send End With Set mitOutlookMsg = Nothing Set appOutlook = Nothing MsgBox "Emails have been sent" End If Next Cell End Sub
当单元格为空时, Cell.Value <= Date + 30
将始终返回TRUE
。
移动ElseIf IsEmpty(myName) Then
ElseIf Cell.Value <= Date + 30 Then
例如
If IsEmpty(myName) Then MsgBox "Please enter a name" ElseIf Not IsDate(Cell.Value) Then MsgBox "Please make sure all dates are in a valid form: DD.MM.YYYY" ElseIf Cell.Value <= Date + 30 Then Else
编辑:下面的部分在评论中回答你的问题。
如果你不想运行代码,即使一个单元格是空的,那么你可以使用这个代码。 这将检查count of cells = number of cells filled
。 如果它们不相同,则表示一个或多个单元格是空的。
Sub Sample() Dim rng As Range Set rng = Range("P3:P4").Cells If rng.Count <> Application.WorksheetFunction.CountA(rng) Then MsgBox "Please ensure that all cells are filled with dates in the range" Exit Sub End If ' '~~> Rest of the code ' End Sub