Excel单元格合并

合并前: 合并后:


合并宏:

Sub 合并单元格()
    Dim colNum, rowNum, i, m As Integer
    Dim val As String
    val = MsgBox("是否要合并项目,资金账号,类别和品种列重复并连续的单元格?", vbYesNo)
    If val = vbNo Then
        Exit Sub
    End If
    colNum = 4
    rowNum = Cells(65535, colNum).End(xlUp).Row
    If Range("A2").MergeCells = True Or Range("B2").MergeCells = True Then
        Exit Sub
    End If
    
    i = 1
    While i <= rowNum
    
      If Cells(i, 4) = "账号合计" Then
          Range(Cells(i, 3), Cells(i, 3)).ClearContents         
          Range(Cells(i, 3), Cells(i, 4)).Merge                         
          
          Range(Cells(i, 3), Cells(i, 4)).VerticalAlignment = xlCenter
          Range(Cells(i, 3), Cells(i, 4)).HorizontalAlignment = xlCenter
          Range(Cells(i, 3), Cells(i, 4)).Interior.Color = RGB(192, 192, 192)
      End If
      i = i + 1
    Wend
    
    i = 1
    colNum = 1
    While i < rowNum
        m = 1
        While Cells(i + m, colNum) = Cells(i, colNum)
            m = m + 1
        Wend
      
        If m = 1 Then
            i = i + 1
        Else
            Range(Cells(i + 1, colNum), Cells(i + m - 1, colNum)).ClearContents
            Range(Cells(i, colNum), Cells(i + m - 1, colNum)).Merge
            Range(Cells(i, colNum), Cells(i + m - 1, colNum)).VerticalAlignment = xlCenter
            Range(Cells(i, colNum), Cells(i + m - 1, colNum)).HorizontalAlignment = xlCenter
            i = i + m
        End If
    Wend
    
    i = 1
    colNum = 2
    While i < rowNum
        m = 1
        While Cells(i + m, colNum) = Cells(i, colNum)
            m = m + 1
        Wend
      
        If m = 1 Then
            i = i + 1
        Else
            Range(Cells(i + 1, colNum), Cells(i + m - 1, colNum)).ClearContents
            Range(Cells(i, colNum), Cells(i + m - 1, colNum)).Merge
            Range(Cells(i, colNum), Cells(i + m - 1, colNum)).VerticalAlignment = xlCenter
            Range(Cells(i, colNum), Cells(i + m - 1, colNum)).HorizontalAlignment = xlCenter
            i = i + m
        End If
    Wend
    
    i = 1
    While i <= rowNum
    
      If Cells(i, 4) = "项目合计" Then
          Range(Cells(i, 2), Cells(i, 3)).ClearContents           
          Range(Cells(i, 2), Cells(i, 4)).Merge                  
          
          Range(Cells(i, 2), Cells(i, 4)).VerticalAlignment = xlCenter
          Range(Cells(i, 2), Cells(i, 4)).HorizontalAlignment = xlCenter
          Range(Cells(i, 2), Cells(i, 4)).Interior.Color = RGB(192, 192, 192)
      End If
      i = i + 1
    Wend
    
End Sub




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值