VBA Excel自动填充事件

当用户尝试自动填充列时,我需要能够执行一些代码,或者能够在执行Worksheet_Change期间检测到它是自动填充。 我有一些代码来改变自动填充的单元格的值。 问题是这个代码每次我一次编辑几个单元格时触发。

Private Sub Worksheet_Change(ByVal Target As range) If Target.Rows.count > 1 Then 

AFAIK和我可能是错的,但没有简单的方法可以捕捉自动填充事件。

Target.Rows.count是检查是否为自动填充的不可靠方式,因为在许多情况下, Target.Rows.count将大于1。 例如

  1. 用户粘贴在多个单元格中
  2. 用户删除多个单元格
  3. 用户按下CTRL + Z撤消 )改变多个单元格等等…

如果你真的想陷入自动填充,那么你必须处理所有上述情况,并消除缩小范围的可能性,以确定它确实是一个自动填充事件。

 Private Sub Worksheet_Change(ByVal Target As Range) If Target.Count > 1 Or Target.Column <> 1 Then Exit Sub MsgBox Target.Address ' your code goes here End Sub 

所以如果多个单元格被更改,代码将不会被激活,或者如果它不在A列中发生

在更改事件期间,您有2个区域,大部分选定区域的大小与正在更改区域的大小相匹配。 在DragFill操作中,select区域完全包含正在更改的区域,但也包含作为拖动填充源的区域。 源也填充选定区域的一个边缘。

  Application.SheetChange += Sheet_Change; private void Sheet_Change(object Sh, Range Target) { //See if the size of the target matches the size of the current selection. //Selection size must be greater that one cell //Changed cells must be in the same dimension as the unchanged cells. eg unchanged area must fill one edge of the rectangle var selection = (Application.Selection as Range); Rect selectionArea = new Rect(selection.Column, selection.Row, selection.Columns.Count, selection.Rows.Count); Rect changedArea = new Rect(Target.Column, Target.Row, Target.Columns.Count, Target.Rows.Count); var isDragFill = false; if (selectionArea.Contains(changedArea) && (selectionArea.Width > 1 || selectionArea.Height > 1) && (selectionArea.Width == changedArea.Width || selectionArea.Height == changedArea.Height) && selectionArea != changedArea) isDragFill = true; if (!blockNextChange) { if (isDragFill) { //Re-entrancy check in the case the value changes in this block blockChanges = true; bool isHorizontal = selectionArea.Height == changedArea.Height; { if (isHorizontal) { DragFillHorizontal(Target, selection, selectionArea, changedArea); } else { DragFillVertical(Target, selection, selectionArea, changedArea); } } blockChanges = false; } } }