如何将数据从一个表的特定行添加到另一个表

时间:2018-08-03 07:03:42

标签: excel vba excel-vba

如果第一列中的单元格等于某个值,如何复制一组行。

这是我在网上找到的代码,但似乎无法正常工作,因为我将表格上的数据格式化为表格。

Private Sub CommandButton1_Click()
    a = Worksheets("inbd").Cells(Rows.Count, 1).End(xlUp).Row

    For i = 2 To a
        If Worksheets("inbd").Cells(i, 3).Value = 76 Then
            Worksheets("inbd").Rows(i).Copy
            Worksheets("sheet2").Activate
            b = Worksheets("sheet2").Cells(Rows.Count, 1).End(xlUp).Row
            Worksheets("sheet2").Cells(b + 1, 1).Select
            ActiveSheet.Paste
            Worksheets("sheet1").Activate
        End If
    Next

    Application.CutCopyMode = False
    ThisWorkbook.Worksheets("inbd").Cells(1, 1).Select
End Sub

“ inbd”表的外观示例:

example of how table on "inbd" looks

1 个答案:

答案 0 :(得分:0)

接下来,将过滤具有相关条件的A列并将已过滤的行复制到Sheet2中,因为我使用了A列至N列,因此您需要修改范围,也请牢记代码下面,我正在过滤A列以找到值76,而在原始代码中,您正在将C列过滤为代码Cells(i, 3).Value = 76,其中3是列号:

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("inbd")
Dim wsDestination As Worksheet: Set wsDestination = Sheets("Sheet2")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A

ws.Range("A1:N" & LastRow).AutoFilter Field:=1, Criteria1:="76"
'filter data on Column 1 (A), change the Field number from 1 to the column number you wish to filter
ws.Range("A2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy
'copy filtered results
DestinationRow = wsDestination.Cells(wsDestination.Rows.Count, "A").End(xlUp).Row + 1
'get the destination row
wsDestination.Range("A" & DestinationRow).PasteSpecial xlPasteAll
'paste into Sheet2
Application.CutCopyMode = False
'deselect the copied rows
ws.Range("A1:N" & LastRow).AutoFilter Field:=1
'remove filter
End Sub
相关问题