|
最近因为工作关系,经常需要处理各种合并单元格的问题,自己用vba写了一个处理的宏,不过后来想起来搜了一下,好像很少有用两层for循环这种思路来写的,请问是我的思路有问题吗,还是这种做法会有什么效率上的问题,请各位提下意见。
- Attribute VB_Name = "模块1"
- Sub 当前列单元格合并拆分()
- Attribute 当前列单元格合并拆分.VB_ProcData.VB_Invoke_Func = " \n14"
- '
- '当前列单元格合并拆分
- '
- '
- Application.ScreenUpdating = False
- Application.DisplayAlerts = False
- crtcol = Selection.Column
- colheight = ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Row - 1
- 'MsgBox IsEmpty(Cells(3461, 3))
- userinput = CInt(InputBox("请选择功能:" & vbCrLf & "1为所在列相同单元格自动合并" & vbCrLf & "2为所在列空单元格向上合并" & vbCrLf & "3为所在列合并单元格拆分并填充" & vbCrLf & "4为所在列合并单元格拆分不填充", "功能选择"))
- If userinput = 1 Then
- Call colMerge(crtcol, colheight)
- ElseIf userinput = 2 Then
- Call nullMerge(crtcol, colheight)
- ElseIf userinput = 3 Or userinput = 4 Then
- Call colUnMerge(crtcol, colheight, userinput)
- Else
- MsgBox "该模块尚未开发,敬请期待"
- End If
- Application.ScreenUpdating = True
- Application.DisplayAlerts = True
- 'MsgBox crtcol
- 'Call colUnMerge(crtcol, colheight)
- 'Call colMerge(crtcol, colheight)
- End Sub
- Private Sub colUnMerge(crtcol, colheight, userinput)
- For i = 1 To colheight
- With Cells(i, crtcol).MergeArea
- 'MsgBox .Address
- If (.Columns.Count = 1) And (.Rows.Count > 1) Then
- mgheight = .Rows.Count
- .UnMerge
- If userinput = 3 Then
- .Value = Cells(i, crtcol).Value
- End If
- i = i + mgheight - 1
- End If
- End With
- Next
- End Sub
- Private Sub colMerge(crtcol, colheight)
- For i = 1 To colheight
- 'If i > 40 Then
- 'MsgBox i
- 'End If
- If Cells(i, crtcol).MergeCells Then
- i = i + Cells(i, crtcol).MergeArea.Rows.Count - 1
- ElseIf IsEmpty(Cells(i, crtcol)) Then
-
- Else
- j = i
- tmp = Cells(i, crtcol).Value
- Do
- j = j + 1
- Loop While (Cells(j, crtcol).Value = tmp) And (j <= colheight)
- j = j - 1
- If j > i Then
- Range(Cells(i, crtcol), Cells(j, crtcol)).Merge
- End If
- i = j
- End If
- Next
- With Columns(crtcol)
- .HorizontalAlignment = xlCenter
- .VerticalAlignment = xlCenter
- .WrapText = False
- End With
- End Sub
- Private Sub nullMerge(crtcol, colheight)
- For i = 1 To colheight
- 'If i > 40 Then
- 'MsgBox i
- 'End If
- If Cells(i, crtcol).MergeCells Then
- i = i + Cells(i, crtcol).MergeArea.Rows.Count - 1
- Else
- j = i
- Do
- j = j + 1
- Loop While IsEmpty(Cells(j, crtcol)) And (j <= colheight)
- j = j - 1
- If j > i Then
- Range(Cells(i, crtcol), Cells(j, crtcol)).Merge
- End If
- i = j
- End If
- Next
- With Columns(crtcol)
- .HorizontalAlignment = xlCenter
- .VerticalAlignment = xlCenter
- .WrapText = False
- End With
- End Sub
复制代码
|
|