excel 复制行并将其插入表中

doinxwow  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(166)

我正在尝试编写一个代码来完成以下任务:在我的当前活动工作表的表中,我想复制当前单元格的整行(如果可能的话,尊重表A$:K$的列的限制)复制下面的复制信息,目前我有一个代码,为我自动插入行数,就在当前单元格下面,但我想知道是否有可能增加此代码,使其插入这些行已经与单元格的当前行相同的内容,我是的,我尝试了一些代码,但我没有得到任何结果,他们都只是插入行和一些给出的错误,粘贴空间很小,所以我甚至不会把它们放在这里。
我的代码插入行,没有打破表或任何东西(目前工作正常):

Sub INSERIR_LINHAS()

Application.ScreenUpdating = False

    Dim Table As Object
    Dim Rows As Range
    Set Rows = Worksheets("CC").Range("B18") 'Number of rows to be inserted
    Dim rng As Range
    Set rng = ActiveCell
    
If Rows = ("1") Then GoTo ErrHandler

Set Table = ActiveSheet.ListObjects(1)
With Table
    If Not Intersect(Selection, .DataBodyRange) Is Nothing Then
        rng.EntireRow.Offset(1).Resize(Rows.Value - 1).Insert Shift:=xlDown 'Rows must be: Rows-1 because of the row in current cell location
    End If
End With

Exit Sub

ErrHandler:
    Exit Sub

Application.ScreenUpdating = True

End Sub

预期结果的证明:
首先,在本例中,我想复制的行是标为红色Table Header(A3:AK)x1c 0d1x的行
接下来,让我们假设我的代码有信息,它需要复制该行5次以上(它有信息,它需要总共6行)。这将是我想要的结果。

使用@Darren Bartrup-Cook代码,我得到了我想要的结果,只是对代码进行了一些调整,以便在活动的Sheet和Table上工作:

Sub Test()

    Dim MyTable As Object
    Dim RowsToAdd As Long
    RowsToAdd = Worksheets("CC").Range("B18") 
        
    Set MyTable = ActiveSheet.ListObjects(1)
    
    If RowsToAdd > 0 Then
            If Not Intersect(Selection, MyTable.DataBodyRange) Is Nothing Then
            
            Dim SelectedRow As Long
            SelectedRow = Intersect(Selection, MyTable.DataBodyRange).Row - MyTable.HeaderRowRange.Row
            
            Dim RowCounter As Long
            For RowCounter = SelectedRow To SelectedRow + RowsToAdd - 1
                MyTable.ListRows.Add Position:=RowCounter + 1
                MyTable.ListRows(RowCounter).Range.Copy Destination:=MyTable.ListRows(RowCounter + 1).Range
            Next RowCounter
        End If
    End If

End Sub
t3psigkw

t3psigkw1#

应该可以这样做:

Sub Test()

    'Get the table by name and location.
    'Not relying on the correct sheet being active, and the first table being the one you need.
    Dim MyTable As ListObject
    Set MyTable = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
    
    Dim RowsToAdd As Long
    RowsToAdd = ThisWorkbook.Worksheets("Sheet1").Range("E1")

    If RowsToAdd > 0 Then
        If Not Intersect(Selection, MyTable.DataBodyRange) Is Nothing Then
            
            'Calculate which row in the table is selected.
            Dim SelectedRow As Long
            SelectedRow = Intersect(Selection, MyTable.DataBodyRange).Row - MyTable.HeaderRowRange.Row
            
            Dim RowCounter As Long
            For RowCounter = SelectedRow To SelectedRow + RowsToAdd - 1
                MyTable.ListRows.Add Position:=RowCounter + 1
                MyTable.ListRows(RowCounter).Range.Copy Destination:=MyTable.ListRows(RowCounter + 1).Range
            Next RowCounter
        End If
    End If

End Sub

相关问题