利用VBS合并Excel中相同单元格

假如有一份这样的表格

你需要把不同行上相同的单元格进行合并,实现下面的效果

 

可以通过以下步骤用VBS来实现

1. 首先对表格进行排序,排序的这一列也是单元格合并时所参照的列,通常是学号或者ID列等

2. 然后在当前Excel表格中按Alt + F11,调出VBS编辑器,贴入以下代码

Sub mergerow()
    'Declare variables
    Dim lRow As Double      'Last row
    Dim sRow As Double      'Current row
    Dim cValue As String    'Value used to compare
   
    'The reference column
    Dim refCol As Integer
    refCol = 2
   
    'The columns you want to mergen
    Dim merCol As Integer
    merCol = 2
   
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
   
    With ActiveSheet
   
        'Init the variables
        lRow = .Range("A1048576").End(xlUp).Row
        sRow = lRow
        cValue = .Cells(lRow, refCol).Value
       
        For i = lRow - 1 To 1 Step -1
            If .Cells(i, refCol).Value = cValue Then
            Else
                'Only merge two or more cells
                If sRow - i > 1 Then
                    For j = 1 To merCol Step 1
                        .Range(.Cells(i + 1, j), .Cells(sRow, j)).Merge
                    Next
                End If
               
                'Reset the variables
                sRow = i
                cValue = .Cells(i, refCol).Value
            End If
        Next
       
    End With
   
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

3. 然后按F5运行

对于其它格式的表格,通常只需修改下面两个参数:

refCol是合并时所参照的列,如你的学号列是第三列,可以设置该值为3

    'The reference column
    Dim refCol As Integer
    refCol = 3


 merCol是你打算将前多少列进行合并,如你的学号列后面还有性别列, 则可以设置该值为3
    'The columns you want to mergen
    Dim merCol As Integer
    merCol = 3

转载于:https://www.cnblogs.com/fengjunkuan/p/4026926.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值