1、首先打开Microsoft Office Excel 2007,文件保存为《Excel数据重复或+空格怎样批量合并单元格》,如下图。
2、然后按下快捷键ALT+F11打开VBA(宏)编辑界面,然后点菜单栏【插入】下拉中列表中点【模块(M)】如图。
3、然后插入了一个模块1,在代码框中复制如下代码:Option Base 1Sub 选重复空合并单元格() '2020-5-17 22:38:23 Dim myr As Range, r1 As Long, r2 As Long, c1 As Long, c2 As Long Dim k As Long, i As Long, n As Long Set myr = Selection n = myr.Count r1 = myr.Cells(1).Row r2 = myr.Cells(n).Row c1 = myr.Cells(1).Column c2 = myr.Cells(n).Column Application.ScreenUpdating = False If r1 = r2 Or c1 = c2 Then Call ZKDYG Else Response = MsgBox("按列合并单元格请按“是(Y)”,按行合并单元格请按“是(N)”", vbYesNo) If Response = vbYes Then For i = c1 To c2 Range(Cells(r1, i), Cells(r2, i)).Select Call ZKDYG Next i Else For i = r1 To r2 Range(Cells(i, c1), Cells(i, c2)).Select Call ZKDYG Next i End If End If Application.ScreenUpdating = TrueEnd SubPrivate Sub ZKDYG() '2020-5-17 22:18:12 Dim myr As Range, n As Long Dim k As Long, i As Long, j As Long, mb(), mk Set myr = Selection n = myr.Count Application.DisplayAlerts = False k = Application.WorksheetFunction.CountA(myr) If k = 0 Then myr.Merge ElseIf k = n Then j = 0 ReDim mb(n, 2) For i = 1 To n If i = 1 Then j = j + 1 mk = myr.Cells(i).Value mb(j, 1) = i Else If mk <> myr.Cells(i).Value Then j = j + 1 mb(j, 1) = i mk = myr.Cells(i).Value mb(j - 1, 2) = i - 1 End If End If Next i Else j = 0 ReDim mb(n, 2) For i = 1 To n If i = 1 And myr.Cells(i).Value <> "" Then j = j + 1 mb(j, 1) = i Else If myr.Cells(i).Value <> "" Then j = j + 1 mb(j, 1) = i mb(j - 1, 2) = i - 1 End If End If Next i End If mb(j, 2) = n For i = 1 To j Range(myr.Cells(mb(i, 1)), myr.Cells(mb(i, 2))).Merge Next iEnd Sub
4、以上操作动态过程如下:
5、回到工作表窗口,首先选数据表,然后运行【选重复空合并单元格】宏(菜单栏中点【视图】中下列表中【宏】列表【查看宏(V)】打开宏对方框,选该宏名),根据选数据不同有四种结果下面一一分述。