2017-03-07 54 views
1

我试图通过列“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 
+0

Maybe'Cells(i + 13,...'should be'Cells(i + 1,...'? –

+0

将代码更改为'如果Cells(i,13).Value <> Cells(i + 1,13).Value Then'做了这个诀窍。谢谢!! – XLmatters

回答

1

其实你已经作出了这个问题,但要被解答我张贴这个答案对未来有关这一问题的任何搜索假装这。

当你写你的方程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 
+0

@XLmatters顺便说一句,我意识到,在这个例子中,你已经成功地在公式**问题中应用了**变量。 – Mertinc

+0

感谢您的反馈,Mertinc。自从3月7日发布以来,我一直在使用这个子程序,并没有出现呃逆。所以它的测试非常好。 – XLmatters

相关问题