odo*_*doc 2 excel vba excel-vba
我仍然是相当新的宏,我有一些代码,我需要在每次更新,更改或其他任何时候在工作表上运行.
这是我需要运行的代码:我该怎么做?
Sub UnMergeFill()
Dim cell As Range, joinedCells As Range
For Each cell In ThisWorkbook.ActiveSheet.UsedRange
If cell.MergeCells Then
Set joinedCells = cell.MergeArea
cell.MergeCells = False
joinedCells.Value = cell.Value
End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以通过找到要处理的合并单元格而不是循环遍历Worksheet.UsedRange属性中的每个单元格并检查Range.MergeCells属性来提高宏的效率.
在工作表的传统Range.Find方法中,有一个查找格式的选项.在此子对话框的" 对齐"选项卡上,您将找到用于查找" 合并"单元格的选项.
这可以使用Range.Find方法和Application对象的 .FindFormat属性合并到VBA子过程中.
您使用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
Run Code Online (Sandbox Code Playgroud)
稍微修改了Worksheet_Change事件宏,在处理期间关闭了更多环境.
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
Run Code Online (Sandbox Code Playgroud)
我选择指定要处理的工作表而不是依赖ActiveSheet属性.当工作表_Change不是活动工作表时,有可能由外部进程启动.
简而言之,尽可能选择批量操作,并尽可能避免循环.这不是快速致盲,但它应该比循环通过细胞快得多.