Excel 2010 VBA:根据值将行复制到新工作表

时间:2013-11-26 07:26:24

标签: excel vba excel-vba excel-2010

如标题中所述,我试图首先检查特定单元格中的值,然后如果匹配,则将整行复制到新表格中。没有抛出错误但结果为空。 请协助。

Public Function freshSheet(inPart As String)
    Dim mag As Worksheet
    Dim currRow As Long
    Dim iohd As Worksheet
    Dim magCount As Integer

    Set iohd = ActiveWorkbook.Worksheets("IOHD")
    'TODO: Create Magic Sheet.
    Set mag =   ActiveWorkbook.Worksheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
    mag.Name = "Magic"

    'TODO: Iterate through IOHD Sheet.
    For currRow = iohd.Rows.Count To 2 Step -1
        'TODO: IS PART EQUAL TO INPART? IF SO, COPY TO MAGIC SHEET
        If iohd.Cells(currRow, 2).Value = inPart Then
            magCount = mag.UsedRange.Rows.Count + 1
            iohd.Cells(currRow, 2).EntireRow.Copy Destination:=mag.Cells(magCount, 1)
        End If
    Next

End Function

2 个答案:

答案 0 :(得分:2)

试试这个:

Public Function freshSheet(inPart As String)
    Dim mag As Worksheet
    Dim currRow As Long
    Dim iohd As Worksheet
    Dim magCount As Long
    Dim lRow As Long

    Set iohd = ThisWorkbook.Sheets("IOHD")
    'TODO: Create Magic Sheet.
    Set mag =   ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    mag.Name = "Magic"
    lRow = iohd.Cells(Rows.Count, 1).End(xlUp).Row

    For currRow = lRow To 2 Step -1
        If iohd.Cells(currRow, 2).Value = inPart Then
            magCount = mag.UsedRange.Rows.Count + 1
            iohd.Cells(currRow, 2).EntireRow.Copy Destination:=mag.Cells(magCount, 1)
        End If
    Next

End Function

如果有帮助,请告诉我们。 :)

答案 1 :(得分:0)

最后,我尝试了上述方法,发现简单地清除过滤器并重新应用它们要容易得多。 就我个人而言,我并不喜欢这个想法,因为我发现删除某些东西的想法只是为了再添加它;但是,在代码中它更简单。

归功于:Siddharth Rout