运行一个macros,每当表单被改变

我还是相当新的macros,我有一些代码,我需要运行在工作表上每次更新,更改,或任何。

这里是我需要运行的代码:我该怎么做?

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 

在特定工作表的代码模块中,只需添加以下内容:

 Private Sub Worksheet_Change(ByVal Target As Range) Application.EnableEvents = False UnMergeFill Application.EnableEvents = True End Sub 

您可以通过查找合并的单元格来处理而不是循环遍历Worksheet.UsedRange属性中的每个单元格,并检查Range.MergeCells属性,从而提高macros的效率。

在工作表的传统Range.Find方法中 ,可以select查找格式。 在这个子对话框的alignment选项卡上,您将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 

稍微修改了Worksheet_Change事件macros,在处理过程中有更多的环境closures。

 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 

我select了指定要处理的工作表,而不是依赖于ActiveSheet属性 。 Worksheet_Change有可能在不是活动工作表的情况下由外部进程启动。

总之,尽可能select批量操作,并尽可能避免循环。 这不是盲目快速的,但它应该比循环通过细胞快得多。