excel 循环遍历列,同时检查单元格是否为空

zlwx9yxi  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(152)

我试图通过一列循环,同时检查行中的单元格是否为空,以及表中的今天的日期减去日期是否高于或等于7。如果满足要求,请发送电子邮件。

Private Sub Workbook_Open()
Dim myApp As Outlook.Application, mymail As Outlook.MailItem
Dim datum1 As Date
Dim datum2 As Long
Dim danasnji1 As Date
Dim danasnji2 As Long
Dim x As Long
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To lastrow
    If IsEmpty(Cells(x, 10).Value) Then
        x = x + 1
    Else
        datum1 = Cells(x, 10).Value
        datum2 = datum1
        danasnji1 = Date
        danasnji2 = danasnji1
    
        If danasnji2 - datum2 >= 7 Then
            Set myApp = New Outlook.Application
            Set mymail = myApp.CreateItem(olMailItem)
            mymail.To = "examlemail@mail"
            With mymail
                .Subject = "Test"
                .body = "Body Code"
                .Send
            End With
            Cells(x, 10).Font.Color = RGB(255, 0, 0)
        End If
    End If
Next
Set myApp = Nothing
Set mymail = Nothing
End Sub

Excel表格列图片:

此代码发送电子邮件,但循环跳过一些单元格。应该有5封邮件,但它发送了3封。工作的细胞被染成红色。

jv4diomz

jv4diomz1#

永远不要修改循环中的计数变量(在你的例子中是x),它会被For-语句 * 自动 * 递增。

在您的例子中,您在自动增量的基础上增加了它,导致代码在找到“空”行时跳过一行。将代码更改为

For x = 2 To lastrow
    If Not IsEmpty(Cells(x, 10).Value) Then
        datum1 = Cells(x, 10).Value
        datum2 = datum1
        danasnji1 = Date
        danasnji2 = danasnji1
    
        If danasnji2 - datum2 >= 7 Then
            Set myApp = New Outlook.Application
            Set mymail = myApp.CreateItem(olMailItem)
            mymail.To = "examlemail@mail"
            With mymail
                .Subject = "Test"
                .body = "Body Code"
                .Send
            End With
            Cells(x, 10).Font.Color = RGB(255, 0, 0)
        End If
    End If
Next

请注意,您应该限定您的Cells用法:告诉VBA要使用哪个工作表。如果您编写IsEmpty(Cells(x, 10).Value),VBA将假定您要使用活动工作表,但这并不总是您想要的。仔细看How to avoid using Select in Excel VBA

相关问题