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

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

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 

尝试这个:

 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 

让我们知道这是否有帮助。 🙂

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

信贷去:Siddharth路特