VBA比较两张表并replace表1中的值

我有两张表,sheet1和sheet2。

我在Sheet1中有17列,在Sheet2中有14列。

我在sheet1的L列中有ID(ID以D2B和4开头)。 一个ID是11到13位长,而另一个是8位长。 最后,我只需要D2B的ID。

在表2的L列中,我只有从4开始的ID,长度是8digit。 另外,我有列A只包含D2B。

我正在比较第1张和第2张的列(L)。 如果Id存在于Sheet1中,那么我将结果复制到Sheet2的列M. 因为,我只需要用D2B的Id,我检查第2页的列L和M是否匹配,如果它们匹配,那么我从第N页第2列的A列复制相应的ID d2B。

直到这我已经完成编码。

现在,我想查看以ID 4开始的表单1,并且发现它在表单2中具有与D2C Id相对应的核心,那么它应该被复制到表单1的列M,如果没有find,那么列的ID sheet1的L必须复制到M列中。任何人都可以引导我,我怎么能做到这一点

下面是代码,我用于检查sheet1中的值并粘贴到sheet2中。

Sub lookuppro() Dim totalrows As Long Dim Totalcolumns As Long Dim rng As range totalrows = ActiveSheet.UsedRange.Rows.Count Sheets("Sheet2").Select For i = 1 To totalrows Set rng = Sheets("Sheet1").UsedRange.Find(Cells(i, 12).Value) 'If it is found put its value on the destination sheet If Not rng Is Nothing Then Cells(i, 13).Value = rng.Value End If Next End Sub 

下面是代码,我用来检查它们是否匹配并粘贴sheet2中相应的D2C编号。

 Sub match() Dim i As Long Dim lngLastRow As Long Dim ws As Worksheet lngLastRow = range("A1").SpecialCells(xlCellTypeLastCell).Row Set ws = Sheets("Sheet2") With ws For i = 1 To lngLastRow If .Cells(i, 12).Value = .Cells(i, 13).Value Then .Cells(i, 14).Value = .Cells(i, 1).Value Else 'nothing End If Next i End With End Sub 

这是sheet1的示例屏幕截图以及我正在查找的结果 是sheet2的图像。

我在这个解决scheme中整合了danieltakeshi的评论。 这不是最有效率的,但很容易跟踪,并显示了达到相同目的的两种方法。 代码中包含注释。 总的来说,我创build了许多variables:两个专用于每个工作表,一个用于search条件,两个用于确定L范围中的数据范围,两个用于testing每个范围内的单元格,一个可变循环行和一个variables来改变search条件与查找function。

我已经在有用的范围上设置了限制,testing了信息的匹配部分,将D2C#放在Sheet 2中,然后返回到Sheet 1中。我担心你的逻辑不需要重复,重新提取相同的信息两次…即,考虑重新思考这个程序是如何组织的。

代码本身:

 Sub check_values() Dim sh1 As Worksheet, sh2 As Worksheet Dim cell As Range, cell2 As Range, lstcl As Variant, lstcl2 As Variant, rgFnd As Variant Dim n As Double, ID As String Set sh1 = ThisWorkbook.Sheets(1) Set sh2 = ThisWorkbook.Sheets(2) ID = "4" lstcl = sh1.Range("L10000").End(xlUp).Row lstcl2 = sh2.Range("L10000").End(xlUp).Row 'comparing columns L in both sheets For Each cell In sh2.Range("L1:L" & lstcl2) For n = 1 To lstcl If cell = sh1.Range("L" & n) Then 'the cell in column M next to the matching cell is equal to the 4xxxxxxx number cell.Offset(0, 1) = sh1.Range("L" & n) 'the next cell in column N is equal to the D2C number in column A cell.Offset(0, 2) = cell.Offset(0, -11) End If Next Next 'test that each cell in the first sheet corresponds to the located results in the second sheet _ 'and pastes back the D2C number, using the Range.Find function For Each cell2 In sh1.Range("L1:L" & lstcl) If Left(cell2, 1) = ID Then Set rgFnd = sh2.Range("M1:M" & lstcl2).Find(cell2.Value) If Not rgFnd Is Nothing Then cell2.Offset(0, 1) = sh2.Range(rgFnd.Address).Offset(0, 1) End If End If Next End Sub