我创建了一个宏,用于查找具有特定文件名的打开的Excel文件,然后将数据复制到工作表中的特定选项卡。
源数据大约有489k行,但我只需要大约8k行。
如何在粘贴之前添加代码以过滤打开的excel文件中的数据?
谢谢!
Option Explicit
Sub CopyData()
On Error GoTo ErrorHandle
Application.ScreenUpdating = False
Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook
Dim rngToCopy As Range
For Each wB In Application.Workbooks
If Left(wB.Name, 21) = "xxx_xxxxxxxx xxxxxxxx" Then
Set Wb1 = wB
Exit For
End If
Next
If Not Wb1 Is Nothing Then '<~~ check if you actually found the needed workbook
Set wb2 = ThisWorkbook
With Wb1.Sheets(12)
Set rngToCopy = .Range("$A:$AM", .Cells(.Rows.Count, "A").End(xlUp))
End With
wb2.Sheets(2).Range("$A:$AM").Resize(rngToCopy.Rows.Count).Value = rngToCopy.Value
End If
ThisWorkbook.RefreshAll
Application.CutCopyMode = False
'Action
BeforeExit:
Application.ScreenUpdating = True
Exit Sub
'We land here in case of an error
ErrorHandle:
MsgBox Err.Description & " Sub Something"
Resume BeforeExit 'Sends you back to BeforeExit
End Sub
理想情况下,在复制并粘贴从wb1到wb2的范围之前,我会先准备一个过滤器
答案 0 :(得分:0)
在移动-> rngToCopy.Value <-之后以及在EndWith之后添加以下代码
将范围更改为适当的值,并为您过滤字段和条件
ActiveSheet.Range("$A$1:$BI$1801").AutoFilter Field:=47, Criteria1:="MoWe"
Cells.Select
Selection.Copy