2016-06-15 56 views
0

現在,我的代碼說:「如果D列中的任何單元格都匹配這些單詞」「,則將該單元格從列F到H 」。我希望它做的也是合併D列中的兩個單元格,頂部單元格將包含單詞,下面的單元格將爲空白。我也想讓表格逐行合併一行中的3個單元格,就像在F到H之後它會跳過I然後合併J-L。這裏是代碼:在if下使用多個語句來合併VBA中的多個單元組

Sub Merge_PlansourceCategories() 
Dim RgToMerge As String 


For i = 1 To ActiveSheet.Cells(Rows.Count, 4).End(xlUp).row 
    RgToMerge = "" 
    If Cells(i, 4) = "red" or cells (i, 4) = "blue" Then 
    RgToMerge = "$F$" & i & ":$H$" & i + 1   



    'for step loop to make this easier? 
    With range(RgToMerge) 
     .Merge 
     .HorizontalAlignment = xlCenterAcrossSelection 
     .VerticalAlignment = xlCenter 
    End With 

    End If 

Next i 

End Sub 

回答

1

試試這個

Sub Merge_PlansourceCategories() 
    For i = 1 To ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row 
     If Cells(i, 4) = "red" Or Cells(i, 4) = "blue" Then 
      For j = 1 To 2 
       With Range(Cells(i, j * 4 + 2), Cells(i, j * 4 + 4)) 
        .Merge 
        .HorizontalAlignment = xlCenterAcrossSelection 
        .VerticalAlignment = xlCenter 
       End With 
      Next j 
      With Range(Cells(i, 4), Cells(i + 1, 4)) 
       .Merge 
       .VerticalAlignment = xlCenter 
      End With 
     End If 
    Next i 
End Sub 

實在是創建RgToMerge作爲一個字符串,並使用字母列名沒有一點使得它很難增加。