具有合并单元格的VBA格式表

时间:2019-03-20 06:31:15

标签: excel vba merge

我有一个函数可以合并表中的所有单元格(如果整个范围具有相同的值)(例如,如果A1:G1等于A2:B2,它将合并诸如A1&A2,B1&B2等单元格。此处更多:{{3 }}) 现在,我想更改由该功能创建的表的颜色,例如第一行(是否合并或不合并)填充颜色,第二个空白等,但是我不知道是否应该使用合并功能或创建另一个将检测具有合并行等的新表。下面是我的代码:

Sub test()

    Dim i As Long, j As Long, k As Long, row As Long
    row = Cells(Rows.Count, 2).End(xlUp).row
    k = 1
    For i = 1 To row Step 1
        If Cells(i, 1).Value = "" Then Exit For
        If Join(Application.Transpose(Application.Transpose(Range(Cells(i, 1), Cells(i, 3)))), Chr(0)) <> Join(Application.Transpose(Application.Transpose(Range(Cells(i + 1, 1), Cells(i + 1, 3)))), Chr(0)) Then
          If i <> k Then
            For j = 1 To 3 Step 1
                  Application.DisplayAlerts = False
                  Range(Cells(i, j), Cells(k, j)).Merge
                  Application.DisplayAlerts = True
            Next j
          End If
        k = i + 1
        End If
    Next i
End Sub 

2 个答案:

答案 0 :(得分:0)

尝试:

Option Explicit

Sub test1()

    Dim LastColumn As Long, LastRow As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column

        For i = 2 To LastRow Step 2
            .Range(Cells(i, 1), .Cells(i, LastColumn)).Interior.Color = vbGreen '<- You could change the color
        Next i

    End With

End Sub

之前:

enter image description here

之后:

enter image description here

编辑后的解决方案:

Option Explicit

Sub test1()

    Dim rng As Range

    With ThisWorkbook.Worksheets("Sheet1")

        Set rng = .UsedRange

        .ListObjects.Add(xlSrcRange, rng, , xlYes).Name = "Table1"
        .ListObjects("Table1").TableStyle = "TableStyleLight3"

    End With

End Sub

结果:

enter image description here

答案 1 :(得分:0)

所以,一段时间后,我自己弄清楚了。下面是代码:

Dim i As Long, j As Long, k As Long, l As Long, c As Integer
row = Cells(Rows.Count, 2).End(xlUp).row
k = 7
c = 1
For i = 7 To row Step 1
    If Join(Application.Transpose(Application.Transpose(Range(Cells(i, 1), Cells(i, 3)))), Chr(0)) <> Join(Application.Transpose(Application.Transpose(Range(Cells(i + 1, 1), Cells(i + 1, 3)))), Chr(0)) Then
      If i <> k Then
        For j = 1 To 3 Step 1
              Application.DisplayAlerts = False
              Range(Cells(i, j), Cells(k, j)).Merge
              Application.DisplayAlerts = True
        Next j
      End If
    Select Case c
        Case 0
            Range(Cells(k, 1), Cells(k, 3)).Interior.Color = xlNone
            c = 1
        Case 1
            For l = 0 To i - k Step 1
                Range(Cells(k + l, 1), Cells(k + l, 3)).Interior.Color = RGB(217, 225, 242)
            Next l
            c = 0
    End Select
    k = i + 1
    End If
Next i