首页 > 代码库 > 利用VBS合并Excel中相同单元格

利用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 = http://www.mamicode.com/.Cells(lRow, refCol).Value
       
        For i = lRow - 1 To 1 Step -1
            MsgBox (.Cells(i, refCol).Value)
            MsgBox (.Cells(i, refCol).Value = http://www.mamicode.com/cValue)
            If .Cells(i, refCol).Value = http://www.mamicode.com/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 = http://www.mamicode.com/.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

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