首页 文章

在上次使用的行之后插入新行并从上面复制公式和格式

提问于
浏览
1

我想要一个宏,它将找到包含数据的最后一行,然后在下面插入一个新行并从上面复制格式和公式(公式在F列中) . 我每次在同一个地方插入一个新行 . 这可能吗?

这就是我所拥有的:

Sub AddNewRow()
'
' AddNewRow Macro
'

'
    Rows("37:37").Select
    ActiveSheet.Unprotect
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("F36").Select
    Selection.AutoFill Destination:=Range("F36:F37"), Type:=xlFillDefault
    Range("F36:F37").Select
    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingCells:=True, AllowDeletingRows:=True, AllowSorting:=True _
        , AllowFiltering:=True
End Sub

2 回答

  • 0

    您只需要创建变量来查找最后一行和第一行,然后使用它:

    Sub AddNewRow()
    
    
    ' AddNewRow Macro
    
    Dim LastRw As Long, EmptyRw As Long
    
    EmptyRw = WorksheetFunction.CountA(Range("F:F")) + 1
    LastRw = WorksheetFunction.CountA(Range("F:F"))
    
    Cells(EmptyRw, 6).Select
    ActiveSheet.Unprotect
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Cells(LastRw, 6).Select
    Selection.AutoFill Destination:=Range(Cells(LastRw, 6), Cells(EmptyRw, 6)), Type:=xlFillDefault
    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingCells:=True, AllowDeletingRows:=True, AllowSorting:=True _
        , AllowFiltering:=True
    
    End Sub
    
  • 0

    可以使用 CurrentRegion 查找最后一行并从那里填写...

    Sub AddNewRow()
    
    ActiveSheet.Unprotect
    ActiveSheet.Range("A1").CurrentRegion.Offset(ActiveSheet.Range("A1").CurrentRegion.Rows.Count - 1).Resize(2).FillDown
    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
        , AllowFormattingCells:=True, AllowDeletingRows:=True, AllowSorting:=True _
        , AllowFiltering:=True
    
    End Sub
    

    如果工作表内容没有在单元格 A1 中开始或在单元格旁边,则需要更改 Range("A1")

相关问题