2017-03-07 57 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

相關問題