查找在两个不同列中包含两个单元格值的行

时间:2018-07-19 20:30:41

标签: excel vba excel-vba

我写了一对If语句来检查两个单元格中两列的值(例如,检查Column A中的B3.Value,检查Column G中的B2.Value),只是意识到这不会返回结果基于同一行中存在的值,但前提是它们完全存在于表中。

我的目标是检查代码以查看是否存在A列中的B3.Value和G列中Bem.Value的行。这些列位于表的DataBodyRange中(因为范围是动态的)。现在,我得到的错误代码是

Dim tblData As ListObject
Dim checkDate As Date
Dim reportSup As Range
Dim reportDate As Range

Set tblData = Worksheets("Data").ListObjects(1)
Set reportSup = Worksheets("Daily").Range("B2")
Set reportDate = Worksheets("Daily").Range("B3")

  checkDate = WorksheetFunction.Max(Worksheets("Data") _
    .ListObjects("Data") _
    .ListColumns("Date") _
    .DataBodyRange)

  If reportDate.Value = checkDate Then

    If Not IsError(Application.Match(reportSup.Value, _
      tblData.ListColumns(7).DataBodyRange, 0)) Then

      MsgBox "You have already reported for this period. " & _
        "Please enter a different date."
      reportDate.Select
      Exit Sub

    End If

  End If

我不确定是否应该使用EVALUATE或INDEX来找到满足两个条件的行,以便如果存在该行,则弹出MsgBox,否则继续其余代码。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,那么您就可以这样做。它使用“查找”在列A中查找B3值,然后检查相应的列G值。我以为这只能发生一次,所以如果不是这种情况,则需要修改代码。

Sub x()

Dim tblData As ListObject
Dim reportSup As Range
Dim reportDate As Range, rFind As Range, s As String

Set tblData = Worksheets("Data").ListObjects(1)
Set reportSup = Worksheets("Daily").Range("B2")
Set reportDate = Worksheets("Daily").Range("B3")

With tblData.ListColumns(1).DataBodyRange
    Set rFind = .Find(What:=reportDate, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not rFind Is Nothing Then
        s = rFind.Address
        Do
            If rFind.Offset(, 6).Value = reportSup.Value Then
                MsgBox "Both values found in row " & rFind.Row
                Exit Sub
            Else
                Set rFind = .FindNext(rFind)
            End If
         Loop While rFind.Address <> s
    End If
End With

End Sub