用于合并单元格的macros

我有一个Excel文件,列B中有发票号( B2:B14987 ),列CI中有项目ID,列DI中有售价,列EI中有发票折扣价值。

我需要一个macros来合并基于发票号码列的发票折扣值单元格,因为在一张发票中有不同的项目标识号,所以重复发票号码。

例如: B1:B3是相同的发票编号, E1B1:B3中发票的普通折扣值, E2:E3是空白单元格。 所以我想E1:E3E1的值合并。

下面的代码做我认为你所要求的; 像往常一样,如果我误解了,请澄清这个问题,我们会到达那里…

在电子表格中创build一个模块,并粘贴下面的代码:

 Private Sub mergeAndAlign(r As Range) With r .HorizontalAlignment = xlCenter .VerticalAlignment = xlCenter .MergeCells = True End With End Sub Sub mergeAll() ' step through column E ' merge all cells that have the same invoice number ' they are already sorted - and the value we need is in the first cell ' of the block to be merged Dim r As Range Dim prevItem As Range Dim nextItem As Range Dim lastRow, thisRow, rCount As Integer lastRow = [B2].End(xlDown).Row Set prevItem = [E2] Set nextItem = prevItem.End(xlDown) While nextItem.Row <= lastRow Set r = Range(prevItem, nextItem.Offset(-1, 0)) mergeAndAlign r Set prevItem = nextItem Set nextItem = nextItem.End(xlDown) Wend ' do the last item: Set nextItem = Cells(lastRow, 5) ' last valid cell in column E Set r = Range(prevItem, nextItem) mergeAndAlign r End Sub 

运行感兴趣的工作表中的代码。 点击Alt-F8popup“macros”对话框 – 你应该在列表中看到“MergeAll”项(可能是唯一的一个)。 它会带你从这个:

原始电子表格

对此:

合并后的电子表格