比较四列和两列返回?

时间:2017-02-21 18:58:58

标签: excel-vba vba excel

我遇到了问题。我想要完成的是比较四列,如果单元格匹配则返回同一行中的两个单元格。 explaination 举例来说,我将A& B与D& E比较,并在同一行上输出F& G.目的地并不重要,因为我可以改变它。 我所做的只比较了两列,它们有效,但它还添加了不应用于该特定行的其他单元格。

Sub Add_XY()
For Each cell In ThisWorkbook.Sheets("Data").UsedRange.Columns("K").Cells
Dim offs As Long: offs = 2 ' <-- Initial offset, will increase after each match
compareValue = cell.Value & "-" & cell.Offset(, 1).Value
ThisWorkbook.Sheets("Data").Range("K6").Value = compareValue
If Not compareValue = "-" Then

For Each compareCell In ThisWorkbook.Sheets("P&T Data").UsedRange.Columns("AI").Cells
'For Each compareCell In   ThisWorkbook.Sheets("Data").UsedRange.Columns("A").Cells

  If compareCell.Value & "-" & compareCell.Offset(, 1).Value = compareValue Then

  ThisWorkbook.Sheets("Data").Range("K6").Value = compareCell.Value & "-" & compareCell.Offset(, 1).Value 'test return value
    cell.Offset(, offs).Value = compareCell.Offset(, 5).Value
    cell.Offset(, offs + 1).Value = compareCell.Offset(, 6).Value
    offs = offs + 4 ' <-- now shift the destination column by 4 for next match
    Else
    End If

Next compareCell

End If

Next cell
End Sub

1 个答案:

答案 0 :(得分:0)

使用完全按照图片中所示输入的数据。

Sub Test()

For Each cell In ThisWorkbook.Sheets("Data").UsedRange.Columns("A").Cells

    compareValue = cell.Value & "-" & cell.Offset(0, 1).Value

    If Not compareValue = "-" Then

    For Each compareCell In ThisWorkbook.Sheets("Data").UsedRange.Columns("A").Cells

        If compareCell.Offset(0, 3).Value & "-" & compareCell.Offset(0, 4).Value = compareValue Then

        cell.Offset(0, 8) = cell.Offset(0, 5)
        cell.Offset(0, 9) = cell.Offset(0, 6)
        Else
        End If

    Next compareCell

    End If

Next cell

End Sub