macros来合并Excel中的两个表

我多次遇到这个问题,从来没有find一个解决问题的令人满意的方法。 我相信这一定是一个简单的macros。 我得到了一张大桌子上的名字,在列中的月份和价值观。 像这样的例子:

Jan-17 Feb-17 Mar-17 CS 12 10 9 GS 1 5 3 JPM 43 35 40 UBS 11 15 13 

每个月我都会得到新的价值,但问题是:名字不一定相同。 有几个新名字和一些不再出现的旧名字。 比如说这个例子:

  Apr-17 BNP 21 Citi 75 CS 11 UBS 8 

我需要将其添加到原来的大表。 所以,我需要为这个月的新东西添加一个满的零排,并在这个月为零的旧东西消失。 我想要这样的结果:

  Jan-17 Feb-17 Mar-17 Apr-17 BNP 0 0 0 21 Citi 0 0 0 75 CS 12 10 9 11 GS 1 5 3 0 JPM 43 35 40 0 UBS 11 15 13 8 

我现在所得到的最好的解决scheme是循环思考两个表中的名称并进行比较。 当它发现不匹配时,检查主表中的下一个名称,如果这两个匹配,则意味着一个新名称。 如果不是,我检查新表中的下一个名称,如果匹配,则表示这是一个已经停止出现的旧名称。 看到我的代码如下:

 Sub FixColumnsNames() 'This sub Compare the names in the Summary and the Input tab and put the same names on both Dim LoopRow As Integer LoopRow = 1 While Sheets("Input").Range("A" & LoopRow) <> "Grand Total" 'Walkthought tha name list until we find the end (Grand Total) If Sheets("Input").Range("A" & LoopRow).Value <> Sheets("Summary").Range("A" & LoopRow).Value Then 'If two names don't match lets analyse: If Sheets("Input").Range("A" & LoopRow + 1).Value = Sheets("Summary").Range("A" & LoopRow).Value Then 'New Strategy Sheets("Summary").Rows(LoopRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Sheets("Summary").Range("A" & LoopRow).Value = Sheets("Input").Range("A" & LoopRow).Value End If If Sheets("Input").Range("A" & LoopRow).Value = Sheets("Summary").Range("A" & LoopRow + 1).Value Then 'Old strategy (it has stopped apearing) Sheets("Input").Rows(LoopRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Sheets("Input").Range("A" & LoopRow).Value = Sheets("Summary").Range("A" & LoopRow).Value End If End If LoopRow = LoopRow + 1 Wend End Sub 

这假设名称总是按字母顺序缩短,但这对我来说不是问题。 这不是一个很好的解决scheme,因为当连续出现两个新名字或新名字时(例如),它将失败。

有人可以请build议如何解决这个问题? 一些代码或伪代码将不胜感激。 谢谢。

你可以用Vlookup公式解决这个问题。 首先,find新的四月值。 你可以用Vlookup April值和表值来做到这一点。

在这里输入图像说明

现在copy/PasteValue值在您的主表下方找不到(具有#N / A Vlookup值的值),并在单元格E2使用此公式(根据需要调整范围) =IFERROR(VLOOKUP(A2,$H$1:$I$10,2,FALSE),0) 。 将公式拖动到底部。

在这里输入图像说明