在M列更改时合并范围

我正在尝试正确的代码,当数字在列“M”中更改时,将合并列“D”到“L”。

我有下面的代码,但它所做的是将从底部到第2行的每一行合并,而不pipe列“M”中的值如何。

我错过了什么?

Sub Merge_Upon_Change() 'Purpose: Merges cells between columns "D" and "L" when column "M" changes Dim r As Long, i As Long Application.DisplayAlerts = False 'Turn off windows warning popup r = Cells(Rows.Count, "D").End(xlUp).row ' find last cell in Column D For i = r To 2 Step -1 If Cells(i, 13).Value <> Cells(i + 13, 13).Value Then 'upon change in column M = 13 Range("D" & i & ":L" & i).Merge 'then merge column "D" through "L" End If Next i Application.DisplayAlerts = True ''Turn on Windows warning popup End Sub 

其实你已经提出这个问题,但假装没有回答我发布这个答案为今后任何search这个问题。

当你写公式为M i <> M i + 13时,它简单地find每一个等式为 (因为可能i + 13不等于你的第i行),因此合并从底部到第2行你的For循环直到2

 Sub Merge_Upon_Change() 'Purpose: Merges cells between columns "D" and "L" when column "M" changes Dim r As Long, i As Long Application.DisplayAlerts = False 'Turn off windows warning popup r = Cells(Rows.Count, "D").End(xlUp).row ' find last cell in Column D For i = r To 2 Step -1 If Cells(i, 13).Value <> Cells(i + 1, 13).Value Then 'upon change in column M = 13 Range("D" & i & ":L" & i).Merge 'then merge column "D" through "L" End If Next i Application.DisplayAlerts = True ''Turn on Windows warning popup End Sub