应用过滤器粘贴后,粘贴到新工作表中

时间:2015-10-26 13:33:42

标签: excel excel-vba vba

我正在尝试运行一个宏,它应该获取最后一个活动行,将所有数据复制到新工作表,应用过滤器(K行上的数字> 15,9),将结果复制并粘贴到一个新表。

但是,在使用过滤器后,新工作表中不会粘贴任何内容。 有什么想法吗?

谢谢!

Sub Macro1()

'Select and paste all data, couldn't work on a "last active line" in here..
Cells.Select
Selection.Copy
Sheets("Plan2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range("A1:O1").Select    
Application.CutCopyMode = False

'Aplying the filter
Selection.AutoFilter
ActiveSheet.Range("$A$1:$O$1056").AutoFilter Field:=11, Criteria1:=">15,9" _
    , Operator:=xlAnd

'Here I'm trying to past the filtered data in the new sheet, but the result appears in blank
Cells.Select
Selection.Copy
Sheets("Plan3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

'Here i came back and turned the autofilter off, but it was useless
Sheets("Plan2").Select
Application.CutCopyMode = False
ActiveSheet.Range("$A$1:$O$1056").AutoFilter Field:=11
End Sub

1 个答案:

答案 0 :(得分:4)

您在代码中遇到一些问题:

  1. 使用Cells可能非常棘手,尤其是当您没有很好地定义它们时
  2. 使用Select绝不是一个好习惯。只需坚持直接使用对象(表格,范围,工作簿等)。
  3. 我不知道您为什么需要将整个数据集复制到新工作表,然后将其过滤以复制到第3张工作表。只需过滤原始数据集并复制到最终工作表即可。我没有为此调整代码,因为您可能需要这样做,但是您知道,您可以使用原始数据而无需复制到另一个工作表进行过滤的中间步骤。
  4. 您可能需要在15.9而非15,9上进行过滤,即使逗号是小数点分隔符也是如此。 (这可能不是真的,但是如果是的话我会加入它(我没有在Excel中使用欧洲系统的经验。)另外,请参阅上面的David Zemens评论。
  5. 在下面的代码中,我已经对所有工作表和范围进行了限定,找到了最后一行并提供了我做出一些假设的注释。修改它以适合您的确切结构,并告诉我它是否有效。

    Sub Macro1()
    
    'Select and paste all data, couldn't work on a "last active line" in here..
    
    Dim wsCopy As Worksheet, wsPlan2 As Worksheet, wsPlan3 As Worksheet
    Set wsCopy = Sheets("mySheet") ' replace with correct sheet name
    Set wsPlan2 = Sheets("Plan2")
    Set wsPlan3 = Sheets("Plan3")
    
    'this will copy only cells with data in (*note -> this could copy more than that, but I will not go into it, for now, it's sufficient to use this)
    With wsCopy
    
        'find last row
        Dim lRow As Long
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
    
        .Range("A1:O" & lRow).Copy 'assume the data goes to column O, change if need be
    
    End With
    
    With wsPlan2
    
        'paste to sheet Plan 2
        .Range("A1").PasteSpecial xlPasteValues
    
        'find last row
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
    
        With .Range("A1:O" & lRow)
            'Aplying the filter
            .AutoFilter 11, ">15,9" 'you may need to use 15.9 here if you indeed mean 15 and 9/10ths. even if the comma separator is what you use to show decimals
            .Copy
        End With
    
        wsPlan3.Range("A1").PasteSpecial xlPasteValues 'change range reference if you need it
    
        .AutoFilterMode = False
    
    End With
    
    End Sub
    
相关问题