2016-06-14 90 views
1

我試圖讓這段代碼說:「如果第3列(C)中的單元格=單詞」高「或」中「,則合併並居中匹配單元格在第4列(D)中只有它下面的單元格,但是現在我的反應方式是通過合併到底部,因爲.End(xlDown)。我不知道如何解決這個問題。數據的,我怎麼想它看起來:使用if語句和for循環來合併某些單元格的VBA

example2

這是我一直在使用VBA代碼:

Sub Merge_Priority2() 
Dim RgToMerge As String 


For i = 1 To ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row 
    RgToMerge = "" 
    If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then 
     RgToMerge = "$D$" & Cells(i, 4).End(xlDown).Row & ":$D$" & i 
     With Range(RgToMerge) 
      .Merge 
      .HorizontalAlignment = xlCenterAcrossSelection 
      .VerticalAlignment = xlCenter 
     End With 

    Else 
    End If 

Next i 

End Sub 
+1

我想只是刪除'.END(xlDown)' 。 –

+0

不,它只是將它不合並的單元居中,然後 – beks123

回答

1

我假設你使用那.End(xlDown)爲了選擇一行,但你可以擺脫(如@MattCremeens建議)。然後,您範圍的第二部分,加1 i得到它選擇只有一個排下來,就像這樣:

RgToMerge = "$D$" & i & ":$D$" & i + 1 

對於行1,RgToMerge然後將看起來像$D$1:$D$2。完全分區是這樣的:

Sub Merge_Priority2() 
Dim RgToMerge As String 


For i = 1 To ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row 
    RgToMerge = "" 
    If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then 
     RgToMerge = "$D$" & i & ":$D$" & i + 1 
     With Range(RgToMerge) 
      .Merge 
      .HorizontalAlignment = xlCenterAcrossSelection 
      .VerticalAlignment = xlCenter 
     End With 

    Else 
    End If 

Next i 

End Sub 
+0

完美。謝謝! – beks123

1

儘量只定義

Sub Merge_Priority2() 
Dim RgToMerge As Range 


For i = 1 To ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row 
    If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then 
    Set RgToMerge = ActiveSheet.Range(Cells(i, 4), Cells(i + 1, 4)) 

     With RgToMerge 
      .Merge 
      .HorizontalAlignment = xlCenterAcrossSelection 
      .VerticalAlignment = xlCenter 
     End With 

    Else 
    End If 

Next i 

End Sub 
0

根據您行變量(i)的範圍內,我稍微修改代碼。我不覺得你離得太遠了。

子Merge_Priority2() 昏暗RgToMerge作爲範圍

For i = 1 To ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row 
    If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then 
     Set RgToMerge = Range(Cells(i, 3), Cells(i + 1, 3)) 
     With RgToMerge 
      .Merge 
      .HorizontalAlignment = xlCenterAcrossSelection 
      .VerticalAlignment = xlCenter 
     End With 

    Else 
    End If 

Next i 

我假設相關的數據是在C列 結束小組