合并范围随着列M中的变化而改变
问题描述:
我试图通过列“M”中的数字更改将合并列“D”到“L”的代码。合并范围随着列M中的变化而改变
我有以下代码,但它所做的全部操作是从底部到第2行合并每一行,而不管列“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
答
其实你已经作出了这个问题,但要被解答我张贴这个答案对未来有关这一问题的任何搜索假装这。
当你写你的方程Mi个 <>Mi个+ 13那么它只是每个方程发现真(因为可能1 + 13个行不等于你为第i个行),并在此它结合了一切,从底部到第二排为您For循环是直到
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
Maybe'Cells(i + 13,...'should be'Cells(i + 1,...'? –
将代码更改为'如果Cells(i,13).Value Cells(i + 1,13).Value Then'做了这个诀窍。谢谢!! – XLmatters