如何在范围中插入新行并复制公式

时间:2010-04-11 07:50:19

标签: excel vba excel-vba

我有一个命名范围,如下面的A2:D3

ITEM    PRICE   QTY SUBTOTAL
1           10  3   30
1           5   2   10
           TOTAL:   40

我要使用VBA将新行插入复制公式而不是值的范围。

非常感谢任何提示/链接。

6 个答案:

答案 0 :(得分:11)

这应该这样做:

Private Sub newRow(Optional line As Integer = -1)
Dim target As Range
Dim cell As Range
Dim rowNr As Integer

    Set target = Range("A2:D3")

    If line <> -1 Then
        rowNr = line
    Else
        rowNr = target.Rows.Count
    End If

    target.Rows(rowNr + 1).Insert
    target.Rows(rowNr).Copy target.Rows(rowNr + 1)
    For Each cell In target.Rows(rowNr + 1).Cells
        If Left(cell.Formula, 1) <> "=" Then cell.Clear
    Next cell
End Sub

答案 1 :(得分:4)

如果您开始录制宏并实际执行任务,它将为您生成代码。完成后,停止录制宏,然后您将获得所需的代码,然后您可以修改。

答案 2 :(得分:1)

答案 3 :(得分:1)

我需要推出一个解决方案,其工作方式类似于数据连接查询扩展结果范围的方式,并且可选择自动填充公式向右移动。也许两年后的赏金迟了,但无论如何我很乐意分享!

Public Sub RangeExpand(rangeToExpand As Range, expandAfterLine As Integer, Optional linesToInsert As Integer = 1, Optional stuffOnTheRight As Boolean = False)
    Debug.Assert rangeToExpand.Rows.Count > 1
    Debug.Assert expandAfterLine < rangeToExpand.Rows.Count
    Debug.Assert expandAfterLine > 0

    If linesToInsert = 0 Then Exit Sub
    Debug.Assert linesToInsert > 0

    Do
        rangeToExpand.EntireRow(expandAfterLine + 1).Insert
        linesToInsert = linesToInsert - 1
    Loop Until linesToInsert <= 0

    If stuffOnTheRight Then
        rangeToExpand.Item(expandAfterLine, rangeToExpand.Columns.Count + 1).Select
        Range(Selection, Selection.End(xlToRight)).Select
        Range(rangeToExpand.Item(expandAfterLine, 1), Selection).Select
    Else
        Range(rangeToExpand.Item(expandAfterLine, 1), rangeToExpand.Item(expandAfterLine, rangeToExpand.Columns.Count)).Select
    End If
    Selection.AutoFill Destination:=Range(rangeToExpand.Item(expandAfterLine, 1), rangeToExpand.Item(rangeToExpand.Rows.Count, Selection.Columns.Count))
End Sub

答案 4 :(得分:1)

本答复针对@marg目前接受的答案解决了以下3个问题,该答案最初发布于4月13日和10日9:43。

  1. target.Rows(rowNr + 1).Insert:1.1。不会将命名范围扩展一行(AFAIK是通过插入行隐式执行此操作的唯一方法(显式修改范围定义),并且在指定的行#后通过行#&#执行此操作 39; s 1到Count - 1)和1.2)仅将target范围中的列向下移动一行。在许多(可能是大多数)情况下,target范围右侧和/或左侧的列也需要向下移动。

  2. target.Rows(rowNr).Copy target.Rows(rowNr + 1)不会复制 通常情况下通常也不需要的格式。

  3. Private Sub InsertNewRowInRange(_    TargetRange作为范围,_    可选InsertAfterRowNumber为Integer = -1,_    可选InsertEntireSheetRow As Boolean = True)

    ' -- InsertAfterRowNumber must be 1 to TargetRange.Rows.Count - 1 for TargetRange to be extended by one Row and for there to be
    ' --    Formats and Formulas to copy from (e.g. can't be 0).  Default: If -1, defaults to TargetRange.Rows.Count.
    ' --    Recommend dummy spacer Row at the bottom of TargetRange which, btw, would also be necessary to manually extend a Range
    ' --    by one Row implicitly via Insert Row (vs. explicilty via changing Range definition).
    
            If InsertAfterRowNumber = -1 Then
                InsertAfterRowNumber = TargetRange.Rows.Count
            End If
    
            If InsertEntireSheetRow Then
                TargetRange.Cells(InsertAfterRowNumber + 1, 1).Select
                Selection.EntireRow.Insert
            Else
                TargetRange.Rows(InsertAfterRowNumber + 1).Insert
            End If
    
            TargetRange.Rows(InsertAfterRowNumber).Select
            Selection.Copy
    
            TargetRange.Rows(InsertAfterRowNumber + 1).Select
            Selection.PasteSpecial _
                Paste:=xlPasteFormats, _
                Operation:=xlNone, _
                SkipBlanks:=False, _
                Transpose:=False
            Selection.PasteSpecial _
                Paste:=xlPasteFormulas, _
                Operation:=xlNone, _
                SkipBlanks:=False, _
                Transpose:=False
    
            Application.CutCopyMode = False
    
        End Sub
    

答案 5 :(得分:0)

这是@Tom回答的另一个解决方案。它不使用&#34;选择&#34;,并且可以插入多行。

' Appends one or more rows to a range.
' You can choose if you want to keep formulas and if you want to insert entire sheet rows.
Private Sub expand_range( _
                        target_range As Range, _
                        Optional num_rows As Integer = 1, _
                        Optional insert_entire_sheet_row As Boolean = False, _
                        Optional keep_formulas As Boolean = False _
                        )

    Application.ScreenUpdating = False
    On Error GoTo Cleanup

    Dim original_cell As Range: Set original_cell = ActiveCell
    Dim last_row As Range: Set last_row = target_range.Rows(target_range.Rows.Count)

    ' Insert new row(s) above the last row and copy contents from last row to the new one(s)
    IIf(insert_entire_sheet_row, last_row.Cells(1).EntireRow, last_row) _
        .Resize(num_rows).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
    last_row.Copy
    last_row.Offset(-num_rows).PasteSpecial
    last_row.ClearContents

    On Error Resume Next ' This will fail if there are no formulas and keep_formulas = True
        If keep_formulas Then
            With last_row.Offset(-num_rows).SpecialCells(xlCellTypeFormulas)
                .Copy
                .Offset(1).Resize(num_rows).PasteSpecial
            End With
        End If
    On Error GoTo Cleanup

Cleanup:
    On Error GoTo 0
    Application.ScreenUpdating = True
    Application.CutCopyMode = False
    original_cell.Select
    If Err Then Err.Raise Err.Number, , Err.Description
End Sub