【问题标题】:Auto fill down cell in Excel VBA MacroExcel VBA宏中的自动填充单元格
【发布时间】:2016-07-20 17:40:12
【问题描述】:
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 应该自动填充到下。代码应该有哪些变化?

【问题讨论】:

  • 为什么`ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count` ??stackoverflow.com/questions/71180/…
  • 您的代码在我的电脑上按照您的要求运行。 Check
  • 对于 lastRow,我会比较您的三列,然后从那里获取最后一行。 UsedRange,根据我的经验,并不总是使用我期望的范围。 lastRow = Max(cells(rows.count,2).End(xlUp).Row,cells(rows.count,3).End(xlUp).Row,cells(rows.count,5).End(xlUp).Row 或 LastRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
  • 是的,我已经改成 LastRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row 还是有一些问题,在E列有一些部分没有用宏填充

标签: vba excel autofill


【解决方案1】:

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

【讨论】:

  • 太棒了!很高兴我能提供帮助。
猜你喜欢
  • 2017-01-23
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
相关资源
最近更新 更多