码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-10-17 18:13:58      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   strong   sp   

假如有一份这样的表格

bubuko.com,布布扣

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

 bubuko.com,布布扣

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

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

bubuko.com,布布扣

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
            MsgBox (.Cells(i, refCol).Value)
            MsgBox (.Cells(i, refCol).Value = cValue)
            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

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

标签:style   blog   http   color   io   ar   for   strong   sp   

原文地址:http://www.cnblogs.com/fengjunkuan/p/4026926.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!