我正在尝试运行一个宏,它应该获取最后一个活动行,将所有数据复制到新工作表,应用过滤器(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
答案 0 :(得分:4)
您在代码中遇到一些问题:
Cells
可能非常棘手,尤其是当您没有很好地定义它们时Select
绝不是一个好习惯。只需坚持直接使用对象(表格,范围,工作簿等)。 15.9
而非15,9
上进行过滤,即使逗号是小数点分隔符也是如此。 (这可能不是真的,但是如果是的话我会加入它(我没有在Excel中使用欧洲系统的经验。)另外,请参阅上面的David Zemens评论。在下面的代码中,我已经对所有工作表和范围进行了限定,找到了最后一行并提供了我做出一些假设的注释。修改它以适合您的确切结构,并告诉我它是否有效。
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