使用VBA插入行并自动填充

时间:2017-04-03 12:17:16

标签: vba

我有一个在电子表格中插入一行的宏,我希望它能自动填充新插入行中的公式。

这是我在电子表格中的示例。

修改:在我当前的电子表格中,有10列和几行,但是我只是复制了一列

   ColumnB
    TextA
    TextA
    TextA
    TextA
    TextB
    TextB
    TextB
    TextB
    TextC
    TextC
    TextC
    TextC

以下代码在TextATextBTextC之后添加新行,等等

Sub Insert()

  Dim LastRow As Long
  Dim Cell As Range

Application.ScreenUpdating = False

    LastRow = Sheets("Sheet1").Cells(Rows.Count, 1).End(-4162).Row

    For Each Cell In Sheets("Sheet1").Range("B7:B" & LastRow)
        If Cell.Value <> Cell.Offset(1, 0) Then
            If Cell.Value <> "" Then
                Sheets("Sheet1").Rows(Cell.Row + 1).Insert
            End If
        End If
    Next Cell

Application.ScreenUpdating = True

End Sub

有没有办法自动填充公式?

我想在添加新行之后在我的循环中插入一行代码,例如以下代码。这个问题是Range参数。我不知道在其中指定什么

Selection.AutoFill Destination:=Range("A21:J22"), Type:=xlFillDefault

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情......

Sub Insert()

Dim LastRow As Long
Dim LastCol As Long
Dim i As Long
Dim Cell As Range

Application.ScreenUpdating = False

LastRow = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

'Assuming Row6 is the header row
LastCol = Sheets("Sheet1").Cells(6, Columns.Count).End(xlToLeft).Column

For i = LastRow To 8 Step -1
    If Cells(i, 2) <> "" And Cells(i, 2) <> Cells(i - 1, 2) Then
        Range(Cells(i - 1, 1), Cells(i - 1, LastCol)).Copy
        Cells(i, 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        Range(Cells(i, 1), Cells(i, LastCol)).SpecialCells(xlCellTypeConstants, 3).ClearContents
    End If
Next i
Application.ScreenUpdating = True

End Sub

答案 1 :(得分:0)

As you know your Range you can insert any of the below methods after your 'Next Cell' statement:

Excel.Cells.Range("B7:B" & LastRow).Value = "=MOD(OFFSET(A7,-1,0)+ (A6<>OFFSET(A6,-1,0)),2)" 'or any function you like, e.g. '=SUM(A1+A2)'
Excel.Cells.Range("B7:B" & LastRow).Value = "0"
Excel.Cells.Range("B7:B" & LastRow).NumberFormat = "General"
Excel.Cells.Range("B7:B" & LastRow).FormatConditions.Add(Excel.XlFormatConditionType.xlExpression, Formula1:="=B6=1")