比较多张纸中的两列并提取值

时间:2018-07-14 06:00:20

标签: excel vba excel-vba excel-formula

这可能是一个重复的问题,但是我在任何地方都找不到有效的解决方案。

我的一位客户需要每周更新项目。他们从包含多个列的ERP中下载了一个excel,我必须在最后一列中评论状态。 每周我都会得到一份新副本,所有以前的录入将被清除,然后这对我来说是重复的工作。我只想看看我上周发表的评论,然后将其复制粘贴到新表中。

问题:

  • 新工作表将采用混合顺序。
  • 会有一些新行,有些行会消失。

第1张

enter image description here

第2页

Sheet 2

对于工作表2中的新行,我将手动更新注释。 但是请帮助我复制在sheet1中输入的重复行

寻找一些专家解决方案

谢谢

3 个答案:

答案 0 :(得分:2)

尝试以下代码。它对我有用。

输入工作表(Sheet1):

enter image description here

下面是代码:

Sub Comapre()

Dim TotalNames As Integer

Dim NameInSheet2 As String, PO As String

TotalNames = Worksheets("Sheet2").Range("A1").End(xlDown).Row

For i = 2 To TotalNames

NameInSheet2 = Worksheets("Sheet2").Range("A" & i).Value

PO = Worksheets("Sheet2").Range("B" & i).Value

Worksheets("Sheet1").Activate

'Finds the cell value in Sheet1

Set cell = Cells.Find(What:=NameInSheet2, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)


    If cell Is Nothing Then

        Else

            'If it found the name then it will compare the PO value

            If cell.Offset(, 1).Value = PO Then

                'If Name and Po value matched then comment will be copied to sheet2.

                Worksheets("Sheet2").Range("C" & i) = cell.Offset(, 2).Value

            End If

        End If

    Next


End Sub

输出表(Sheet2):

enter image description here

请让我知道我的答案是否适合您的问题。

答案 1 :(得分:1)

如果我了解你的话,那么简单的VLOOKUP()就可以完成这项工作。

我假设表中的PO编号是唯一的。

您需要制作一张新纸,并查找对此采购订单的最后评论。

在Sheet2中,例如在单元格C2中,您将输入:

=VLOOKUP(B2,Sheet1!B:C,2,FALSE)

这将在Sheet1的B列中查找您的PO nr 4500253(具有完全匹配项),并从C列中返回匹配的行值。如果找不到匹配项,则会返回错误。

答案 2 :(得分:0)

使用Dictionary对象

Option Explicit

Sub main()
    Dim dict As Object
    Dim cell As Range

    Set dict = CreateObject("Scripting.Dictionary")
    With Worksheets("Sheet1")
        For Each cell In .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
            dict.Item(cell.Value2 & "|" & cell.Offset(, 1).Value2) = cell.Offset(, 2).Value2
        Next
    End With

    With Worksheets("Sheet2")
        For Each cell In .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
            If dict.exists(cell.Value2 & "|" & cell.Offset(, 1).Value2) Then cell.Offset(, 2).Value = dict.Item(cell.Value2 & "|" & cell.Offset(, 1).Value2)
        Next
    End With
End Sub
相关问题