将行中的多个值与另一行进行比较并输出不匹配的值 - Excel VBA

时间:2016-09-08 02:48:18

标签: vba excel-vba excel

我正在尝试比较Sheet 1上的一列中的4个值(全部在同一行中),并查看这些4个值是否存在于Sheet 2上另一列中的任何位置。如果没有匹配我想要从工作表1(列CA:CH)中提取8列数据,并将其放在工作表3上。

到目前为止,我只能将一个值一次与下面的代码进行比较,并且无法弄清楚如何调整它。我确实有很多数据要循环,所以我试图避免使用IF语句并递增,因为在我过去的经历中这种情况往往会非常缓慢。

    Sub CompareRowData()

    Application.ScreenUpdating = False

    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim sh3 As Worksheet
    Dim lr1 As Long
    Dim rng1 As Range
    Dim lr2 As Long
    Dim rng2 As Range


    Set sh1 = Sheets("PreWork Tab")
    Set sh2 = Sheets("UR Facility Data")
    Set sh3 = Sheets("Missing Records")

lr1 = sh1.Cells(Rows.Count, 1).End(xlUp).Row
lr2 = sh2.Cells(Rows.Count, 1).End(xlUp).Row

Set rng1 = sh1.Range("CA2:CD" & lr1)
    For Each c In rng1
        If WorksheetFunction.CountIf(sh2.Range("B2:E" & lr2), c.Value) = 0 Then
            'I would like this to export the row data for columns CA through CH from sh1
            sh3.Range("A" & sh3.Cells(Rows.Count, 1).End(xlUp).Row)(2) = c.Value
        End If
    Next


End Sub

1 个答案:

答案 0 :(得分:0)

试试这个。我使用了嵌套的for循环,但我相信这不会减慢进程的速度

Sub CompareRowData()

    Application.ScreenUpdating = False

    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim sh3 As Worksheet
    Dim lr1 As Long
    Dim rng1 As Range
    Dim lr2 As Long
    Dim rng2 As Range
    Dim cnt As Integer
    Dim check As String

    cnt = 2
    Set sh1 = Sheets("PreWork Tab")
    Set sh2 = Sheets("UR Facility Data")
    Set sh3 = Sheets("Missing Records")

    lr1 = sh1.UsedRange.Rows.count
    lr2 = sh2.UsedRange.Rows.count

    For i = 2 To lr1
        For j = 2 To lr2
            check = ""
            For k = 1 To 4
                If sh1.Cells(i, k + 78).Value <> sh2.Cells(j, k + 1).Value Then
                    check = "notfound"
                End If
            Next k
            If check = "" Then
                sh1.Range("CA" & i & ":CH" & i).Copy Destination:=sh3.Range("A" & cnt)
                cnt = cnt + 1
            End If
        Next j
    Next i
End Sub