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

时间:2016-07-20 17:40:12

标签: excel vba excel-vba autofill

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应该自动填充到关闭状态。代码中的变化应该是什么?

1 个答案:

答案 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