Warm tip: This article is reproduced from serverfault.com, please click

excel-查找从一个工作簿到另一工作簿的匹配值行ID

(excel - Find matching value row id from one workbook to another workbook)

发布于 2020-11-27 20:04:53

我有两个Excel Book1.xlsm和Book2.xlsx。Book1在A列中将具有某些值,例如alpha,beta,gamma等(无重复)。而Book2将多次出现Book1值,例如beta,beta,beta,alpha,alpha,gamma,gamma,gamma,gamma,gamma等等。Book2中的值可能未按字母顺序排序,但相同的值将被分组在一起。Book2值也将在A列中。

我在Book1.xlsm中设计了一个宏,该宏应遍历Book1列A中的每个值,并在Book2列A中找到存在相同值的第一行ID。然后应将该行ID复制到Book1的相应列B中。这就是我的宏代码的样子。当我运行时,它失败并显示运行时错误“ 1004”:应用程序定义或对象定义的错误

Option Explicit
Sub Get_Data()
    Dim wb1 As Worksheet
    Dim wb2 As Worksheet
    Dim wb2row As Integer
    Dim i As Integer
    Dim j As Integer
    Const A = "A"
    Const B = "B"



    Set wb1 = Workbooks("Book1.xlsm").Worksheets("Sheet1")
    Set wb2 = Workbooks("Book2.xlsx").Worksheets("Sheet1")

      'Both For loop start from row id 2.
       For i = 2 To wb1.Range("A2", wb1.Range("A2").End(xlDown)).Rows.Count
        For j = 2 To wb2.Range("A2", wb2.Range("A2").End(xlDown)).Rows.Count
  
           wb2row = Application.WorksheetFunction.Match(wb1.Cells(i, A), Range(wb2.Cells(j, A)), 0)
                    wb1.Cells(i, B).Copy (wb2.Cells(j, A))
       
            Exit For ' j loop

    
        Next j
     Next i

End Sub
Questioner
stuart
Viewed
1
Super Symmetry 2020-11-28 14:36:43

你可以让excel为你完成工作。试试这个(经过测试)

Sub Get_Data()
  With Workbooks("Book1.xlsm").Sheets("Sheet1")
    With .Range(.Range("B2"), .Range("A" & Rows.Count).End(xlUp).Offset(0, 1))
      .Formula2 = "=IFERROR(MATCH(A2,[Book2.xlsx]Sheet1!$A:$A,0),"""")"
      .Value2 = .Value2
    End With
  End With
End Sub