【问题标题】:Excel 2010 VBA: Copy a row to a new sheet based on valueExcel 2010 VBA:根据值将行复制到新工作表
【发布时间】:2013-11-26 07:26:23
【问题描述】:

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

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

【问题讨论】:

  • 你好,罗伯特。首先,在WorkbookSheetCell 中使用Active 弊大于利。其次,要获取工作表的最后一行,.Cells(Rows.Count, 1).End(xlUp).Row 是理想的方法。请在下面查看我对您的代码的修改。 :) 此外,从长远来看,将 magCount 声明为 Long 会好得多。
  • 为什么不使用AUTOFILTER
  • 因为工作表 (IOHD) 已被过滤。每次我想这样做时,我都需要重置这些过滤器。我会考虑你的建议 BK。谢谢。
  • 可能也希望看到这一点,因为它涵盖了相同的方法。 link

标签: vba excel excel-2010


【解决方案1】:

试试这个:

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

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

【讨论】:

  • 明天试试这个。今天不在办公室。感谢您的意见!
【解决方案2】:

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

归功于:Siddharth Rout

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多