在Excel VBAmacros中自动填充单元格

Sub AutoFill() Dim x As Long Dim y As Long Dim lastrow As Long Dim lastcolumn As Long Application.ScreenUpdating = False Application.DisplayAlerts = False lastcolumn = ActiveSheet.UsedRange.Column - 1 + ActiveSheet.UsedRange.Columns.Count lastrow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count For x = 2 To lastrow If Cells(x, 2).Value = "" Then Cells(x, 2).Value = Cells(x - 1, 2).Value Cells(x, 3).Value = Cells(x - 1, 3).Value Cells(x, 5).Value = Cells(x - 1, 5).Value End If Next x Application.ScreenUpdating = True End Sub 

使用上面的代码,我的单元格被填满,但最后一行填充到Excel表单的末尾。 在Excel表格栏D中已经填入BCE应该自动填充到下面。 代码中的变化应该是什么?

Excel VBA最后 LookIn:=xlFormulas 使用VBA(和代码示例)在Excel中查找最后 LookIn:=xlFormulas 的完整教程build议在使用LookIn:=xlFormulas确定最后LookIn:=xlFormulas时使用LookIn:=xlFormulas Cells.Find

 lastrow = Find(What:=” * ”, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 

因为你说列D已经填满了我用:

 lastrow = Range("D" & Rows.Count).End(xlUp).Row 

如果列E没有填充,那么Cells(x, 2).Value必须是<> ""

 Sub AutoFill() Dim x As Long Dim y As Long Dim lastrow As Long Dim lastcolumn As Long Application.ScreenUpdating = False Application.DisplayAlerts = False lastcolumn = ActiveSheet.UsedRange.Column - 1 + ActiveSheet.UsedRange.Columns.Count lastrow = Range("D" & Rows.Count).End(xlUp).Row For x = 2 To lastrow If Cells(x, 2).Value = "" Then Cells(x, 2).Value = Cells(x - 1, 2).Value If Cells(x, 3).Value = "" Then Cells(x, 3).Value = Cells(x - 1, 3).Value If Cells(x, 5).Value = "" Then Cells(x, 5).Value = Cells(x - 1, 4).Value Next x Application.ScreenUpdating = True End Sub