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
B
已填写C
列。 E
应该自动填充到关闭状态。代码中的变化应该是什么?
答案 0 :(得分:1)
Excel VBA Last Row: The Complete Tutorial To Finding The Last Row In Excel With VBA (And Code Examples)建议在使用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