2017-04-03 70 views
-1

我有一個宏在電子表格中插入一行,我希望它自動填充新插入行中的公式。使用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 
+0

添加類似範圍(小區,cell.offset(1,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 
0

當你知道你的範圍,你可以在您的「下一步將任何的下面方法單元」聲明:

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")