Excel VBA 宏中的自动填充单元格

Auto fill down cell in Excel VBA Macro

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 sheet 的末尾。在 Excel sheet 列中 D 已经填充在 B 列中 C & E 应该自动向下填充。代码中应该有哪些变化?

Excel VBA Last Row: The Complete Tutorial To Finding The Last Row In Excel With VBA (And Code Examples)建议在使用Cells.Find.

确定最后一个时使用LookIn:=xlFormulas
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