Microsoft Excel 提供了丰富的快捷键,使得操作电子表格十分方便,尤其是在操作很大,很长的表时。
Excel的自动填充功能,使得复制单元格内容、公式和填充序列的操作变得简单。但是,Excel只提供了通过拖动填充柄来实现填充,并没有为自动填充提供快捷键。在操作十分频繁的时候,右手必须在键盘和鼠标之间来回移动,容易疲劳。系统不提供,作为程序员,可以自己编写一个VBA宏执行自动填充,并为该宏指定快捷键,从而实现通过快捷键执行自动填充操作。
1: 新建一个Excel工作簿;在VBA编辑器中添加一个模块,编写宏代码。
源码:
' Author: Ken Yang
' http://www.cnblogs.com/kenyang
' 使用和分发,请保留完整作者信息。
Sub AutoFill()
Dim SourceArea As Range, TargetArea As Range
Set SourceArea = Selection.Areas.Item(1)
Dim SourceBottomLeftCell As Range, SourceBottomRightCell As Range
Set SourceBottomLeftCell = SourceArea.Cells(SourceArea.Rows.Count, 1)
Set SourceBottomRightCell = SourceArea.Cells(SourceArea.Rows.Count, SourceArea.Columns.Count)
Dim TargetLastRow As Long, TargetLastCell As Range
If SourceBottomLeftCell.Offset(1, 0).Value = vbEmpty Then
If SourceBottomLeftCell.End(xlDown).Value = vbEmpty Then
If SourceBottomLeftCell.Column = 1 Then
If SourceBottomRightCell.Offset(1, 1).Value <> vbEmpty Then
Set TargetLastCell = SourceBottomRightCell.Offset(0, 1).End(xlDown).Offset(0, -1)
End If
Else
If SourceBottomLeftCell.Offset(1, -1).Value <> vbEmpty Then
Set TargetLastCell = SourceBottomLeftCell.Offset(0, -1).End(xlDown).Offset(0, SourceArea.Columns.Count)
End If
End If
Else
Set TargetLastCell = ActiveSheet.Cells(SourceBottomLeftCell.End(xlDown).Offset(-1, 0).Row, SourceBottomRightCell.Column)
End If
Else 'If SourceBottomLeftCell.Offset(1, 0).Value <> vbEmpty Then
Dim LastCell As Range
Set LastCell = SourceBottomLeftCell.End(xlDown)
Dim i As Long, LastRow As Long
LastRow = SourceBottomLeftCell.End(xlDown).Row
For i = 2 To SourceArea.Columns.Count
If SourceArea.Cells(SourceArea.Rows.Count, i).Offset(1, 0).Value = vbEmpty Then
LastRow = SourceBottomLeftCell.Row
Exit For
Else
Dim CurrentLastCell As Range
Set CurrentLastCell = SourceArea.Cells(SourceArea.Rows.Count, i).End(xlDown)
If CurrentLastCell.Row < LastCell.Row Then
LastRow = CurrentLastCell.Row
End If
End If
Next i
Set TargetLastCell = ActiveSheet.Cells(LastRow, SourceBottomRightCell.Column)
End If
If Not TargetLastCell Is Nothing Then
Dim TargetAreaName As String
TargetAreaName = SourceArea.Cells(1, 1).Address(0, 0) & ":" & TargetLastCell.Address(0, 0)
Set TargetArea = Range(TargetAreaName)
On Error GoTo ErrHandler
SourceArea.AutoFill Destination:=TargetArea
TargetArea.Select
End If
ErrHandler:
End Sub
2: 为宏指定快捷键 Ctrl + E。 使用Ctrl + E 作为快捷键的原因是 Ctrl + E 没有被Excel内置功能占用,并且Ctrl 键和 E 键都在键盘的左边区域,左手单手就可以操作。
3: 将工作簿另存为 Excel 加载宏。
4: 将Excel加载宏 复制到 %programfiles%\Microsoft Office\Office12\XLSTART 目录(Excel 2003 目录:%programfiles%\Microsoft Office\Office11\XLSTART),以便Excel启动时,自动加载宏代码。
也可从这里下载宏文件,解压后直接放置到%programfiles%\Microsoft Office\Office12\XLSTART 目录,即可使用。下载的宏文件只支持Excel 2007。如果是Excel 2003, 请按照前面的步骤操作。
这样,可以在Excel 中按下 Ctrl + E 实现向下自动填充了。
缺陷:
VBA宏代码执行的操作,不支持撤销(undo)。
报告bug,请留评论。