代码不检查空字符串

时间:2014-08-11 10:26:06

标签: excel vba excel-vba

我不确定为什么我的代码没有输出我的消息,即使我的电子表格有一个空字段。如果我在消息框中显示它显示为空的值,那么不确定它为什么不在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

1 个答案:

答案 0 :(得分:5)

当单元格为空时,

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
相关问题