【问题标题】:Using for each to compare multiple columns in each workbooks and copy a third colum over to one of the workbooks使用 for each 比较每个工作簿中的多个列,并将第三列复制到其中一个工作簿
【发布时间】:2020-02-18 17:46:13
【问题描述】:

我将新工作簿中的两列与工作簿 2 中的两列相匹配,然后从 Workbook2 中检索 B 列并将其复制到新工作簿中的 B 列。一些单元格将是空的。运行以下代码不会复制任何内容。我不确定我是否使用正确的方法来检索信息。

    Sub InsertDeviceName_NewBook()

      Dim w1 As Worksheet, w2 As Worksheet, wsnew As Worksheet
      Dim wbnew As Workbook
      Dim c As Range, FR As Variant
      Dim d As Range
      Dim e As Range, rng1 As Range, rng2 As Range
      Dim lr1 As Long, lr2 As Long


      Application.ScreenUpdating = False


      Set w2 = Workbooks("Book2.xlsx").ActiveSheet
      Set w1 = Workbooks("Book1.xlsx").ActiveSheet



     w1.Range("B:D").Copy
     Set wbnew = Workbooks.Add 'creates new workbook
     Columns("A:A").Select
     ActiveSheet.Paste
     Application.CutCopyMode = False
     ActiveSheet.Name = w1.Name
     Set wsnew = wbnew.ActiveSheet 'sets the active sheet in the new workbook
     lr1 = wsnew.Cells(Rows.count, 1).End(xlUp).Row
     lr2 = w2.Cells(Rows.count, 1).End(xlUp).Row


     wsnew.Sort.SortFields.Add2 Key:=Range("B1"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    With wsnew.Sort
        .SetRange Range("A1:C" & lr1)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
   End With

Columns("B:B").Insert Shift:=xlToRight, _
      CopyOrigin:=xlFormatFromLeftOrAbove

      Range("B1").Select
      ActiveCell.FormulaR1C1 = "Device Name"

      Dim lr3 As Long

      lr3 = wsnew.Cells(Rows.count, 1).End(xlUp).Row

      Set rng1 = wsnew.Range("C2:D" & lr3)
      Set rng2 = w2.Range("C2:D" & lr2)

'create a loop to find matches between columns C and D in the new workbook
'and match with columns C and D in workbook 2, upon a match retrieve the information
'in column B in workbook2 and add it to Columns B in the new workbook

For Each d In rng1
    FR = Application.Match(d, rng2)
    If IsNumeric(FR) Then
    d.Offset(, -1).Value = w2.Range("B" & FR).Value
    End If

Next d

Application.ScreenUpdating = True

End Sub

【问题讨论】:

    标签: excel vba foreach


    【解决方案1】:

    索引匹配公式在这里不起作用吗?这将捕获彼此匹配的值,然后您基本上可以复制结果并粘贴为值。

    此示例使用单个单元格作为返回值,但您可以将其更改为行公式并为每一行返回正确的结果。

    Index Match With Multiple Criteria Example

    【讨论】:

    • 我会看看索引匹配是否有效,谢谢。不幸的是,复制整行将覆盖我要复制到的行的信息。我只需要将一列中的值添加到工作表中。
    • 我不明白您为什么需要“复制整行”。如果不需要真正复制信息,那么我只会实现索引匹配公式。这将为您提供将 workbook2 索引列中的任何匹配信息放入写入公式的单元格的结果。
    • 我认为 Index-Match 是您想要的解决方案,除非我完全错过了一些东西。我建议你学习如何实现它。尝试使用具有单个匹配条件的公式,而不是首先使用多个匹配条件。 youtube.com/watch?v=-H3UmBUIDYI
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多