您可以通过定位要处理的合并单元格而不是循环遍历宏中的每个单元格来提高宏的效率Worksheet.UsedRange 属性 https://msdn.microsoft.com/en-us/library/office/ff840732.aspx并检查它的Range.MergeCells 属性 https://msdn.microsoft.com/en-us/library/office/ff197310.aspx.
在工作表的常规范围内范围查找方法 https://msdn.microsoft.com/en-us/library/office/ff839746.aspx,有一个选项可以查找格式。在此子对话框中结盟选项卡,您将找到定位选项合并单元格.
可以使用以下命令将其合并到您的 VBA 子过程中范围查找方法 https://msdn.microsoft.com/en-us/library/office/ff839746.aspx和应用对象的 https://msdn.microsoft.com/en-us/library/office/ff194565.aspx .FindFormat 属性 https://msdn.microsoft.com/en-us/library/office/ff838023.aspx.
您使用 FindFormat 的子过程:
Sub UnMergeFill(Optional ws As Worksheet)
If ws Is Nothing Then Set ws = ActiveSheet
Dim fndMrg As Range, joinedCells As Range
Application.FindFormat.MergeCells = True
With ws
On Error Resume Next
Set fndMrg = .Cells.Find(What:=vbNullString, SearchFormat:=True)
Do While Not fndMrg Is Nothing
Set joinedCells = fndMrg.MergeArea
fndMrg.MergeCells = False
'fndMrg.UnMerge '???
joinedCells.Value = fndMrg.Value
Set fndMrg = .Cells.Find(What:=vbNullString, SearchFormat:=True)
Loop
End With
Application.FindFormat.MergeCells = False
End Sub
略有修改处理过程中更多环境关闭的事件宏。
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo bm_Safe_Exit
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Call UnMergeFill(Target.Parent)
bm_Safe_Exit:
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
我选择指定要处理的工作表,而不是依赖于。当 Worksheet_Change 不是活动工作表时,外部进程可能会启动 Worksheet_Change。
简而言之,尽可能选择批量操作,并尽可能避免循环。这并不是快得令人眼花缭乱,但它应该比循环单元格快得多。