在Excel中匹配和插入logging

我有两张数据 一张纸具有4个字段的主要Id,另一个具有2个字段的主要Id。

Sheet A Sheet B ID Name Price Type Category ID Name Price 1 S Normal 2 Aus 500 2 N Default 1 Ind 400 

基本上我需要匹配两个工作表的ID,并复制相应的名称和价格在工作表A表单B。我已经尝试了下面的代码,

 Sub Copy() lastrowA = Worksheets("SheetA").Cells(Rows.Count, "A").End(xlUp).Row + 1 Set rngA = Range("A2" & lastrowA) lastrowB = Worksheets("SheetB").Cells(Rows.Count, "A").End(xlUp).Row + 1 Set rngB = Range("A2" & lastrowB) For Each x In rngB For Each y In rngA If x.Value() = y.Value Then ' Copy paste name and price form B to A End If Next Next End Sub 

使用保留字作为macros的名称永远不是一个好主意。 特别是如果您打算在macros中使用.Copy操作。

 Sub MyCopy() Dim lastrowA As Long With Worksheets("SheetA") lastrowA = .Cells(Rows.Count, "A").End(xlUp).Row With .Range("B2:C" & lastrowA) .Formula = "=IFERROR(VLOOKUP($A2, 'SheetB'!$A:$C, COLUMN(B:B), FALSE), """")" .Value = .Value End With End With End Sub 

该批量使用适当的公式填充整个区域,而不循环,然后将返回的值转换为原始值。 任何不匹配都将是空白的,而不是#N/A错误。

是否需要不使用公式来完成? 我不确定我是否错过了一些东西,但是您肯定可以使用VlookupIndex Match

如果从VBAinput公式:

 Cells(2,2).FormulaR1C1 = "=INDEX(Sheet2!R2C2:R3C3,MATCH(RC[-1],Sheet2!RC[-1]:R[1]C[-1],0),1)" Cells(2,3).FormulaR1C1 = "=INDEX(Sheet2!R2C2:R3C3,MATCH(RC[-2],Sheet2!R2C1:R3C1,0),2)" 

然后,您可以在工作表1的ID列中find最后一行,然后在两列中填写公式。 一旦公式已经填满,只需复制并粘贴为值。

 Dim lstRow As Long lstRow = Sheets("Sheet 1").Cells(Rows.Count, 1).End(xlUp).Row '' find last row Range(Cells(2, 2), Cells(lstRow, 3)).FillDown Range(Cells(2, 2), Cells(lstRow, 3)).Copy Cells(2, 2).PasteSpecial Paste:=xlPasteValues 

编辑:您可以使用VBA公式中的lstRowvariables来确保公式在每次自动运行时覆盖整个范围。 如果您不习惯自己创build公式,可以使用Excel中的“loggingmacros”button来获取公式的代码。

你的代码的问题是

 Set rngA = Range("A2" & lastrowA) 

评估为lastRowA = 5的范围(“A25”)。
如果要解决多个单元格,请使用

 Set rngA = Range("A2:A" & lastrowA) 

得到lastRowA = 5的范围(“A2:A5”)。

除此之外,已经提到的配方也是一个很好的解决scheme。