Excel VBA根据2个条件查找行并添加到msgbox

时间:2016-03-22 19:58:19

标签: excel vba excel-vba

我有一个跟踪项目的日志表。我试图找出如何查看每一行,查找A列中是否有ID#,如果是,则检查该行以查看列H中是否有日期。如果缺少日期则为msgbox将在打开时弹出以列出缺少日期的所有ID#。在定义StrID时我的工作原理,但我希望能够找到所有ID#并在msgbox上列出它们。任何指导或正确方向的观点都将受到极大的赞赏。 THX

    Dim rngFound As Range
    Dim strFirst As String
    Dim strid As String
    Dim strDate As String

    strid = "8"
    strDate = vbNullString

    Set rngFound = Columns("a:a").Find(strid, Cells(Rows.Count, "a:a"), xlValues, xlWhole)
    If Not rngFound Is Nothing Then
        strFirst = rngFound.Address
        Do
            If LCase(Cells(rngFound.Row, "h:h").Text) = LCase(strDate) Then
                'Found a match
                MsgBox "ID #" & Cells(rngFound.Row, "a:a").Text & "is open."

            End If
            Set rngFound = Columns("a:a").Find(strid, rngFound, xlValues, xlWhole)
        Loop While rngFound.Address <> strFirst
    End If

    Set rngFound = Nothing

End Sub

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

Sub test()

Dim i As Long
Dim lRow As Long
Dim msg As String

lRow = Cells(Rows.Count, 1).End(xlUp).Row

With ThisWorkbook.ActiveSheet

For i = 2 To lRow

If IsNumeric(.Cells(i, 1).Value) And .Cells(i, 1).Value <> "" Then

    If .Cells(i, 8).Value = "" Then

        If msg = "" Then

            msg = CStr(.Cells(i, 1).Value)

        Else

            msg = msg + ", " + CStr(.Cells(i, 1).Value)

        End If

    End If

End If

Next i

End With

MsgBox msg

End Sub

它循环遍历A列中的每个单元格(ID),当不是空白时AND是一个数字(如果某些值不是ID,而是文本字段),那么如果H列中同一行中的单元格是空白,将其添加到msg,然后在msg的末尾显示一个消息框。

我的测试结果如下:

enter image description here