将筛选的行从文件复制到打开的工作簿

时间:2018-01-05 11:26:36

标签: excel vba excel-vba

我正在尝试打开当前已关闭的工作簿,根据Sel_RC过滤列A(A2是标题),仅复制可见行并粘贴到ThisWorkbook中,表单“LRD”。

Sub Get_RC_Data()

Dim wbSource As Workbook, wbDest As Workbook
Dim wsSource As Worksheet, wsDest As Worksheet
Dim rngSource As Range, rngDest As Range
Dim Sel_RC As Range

Set wbDest = ThisWorkbook
Set wsDest = wbDest.Worksheets("LRD")
Set rngDest = wsDest.Range("A:CY")

Set Sel_RC = wbDest.Worksheets("Summary").Range("B2")

Set wbSource = Workbooks.Open("G:\Folder\File.xlsm")
Set wsSource = wbSource.Worksheets("data")
wsSource.Range("A2").AutoFilter Field:=1, Criteria1:=Sel_RC
Set rngSource = wsSource.Range(wsSource.Range("A2:CY2"), 
wsSource.Range("A2:CY2").End(xlDown)).SpecialCells(xlCellTypeVisible)

rngDest.Value = rngSource.Value

wbSource.Close (False)

End Sub

除了这行之外,一切正常:

Set rngSource = wsSource.Range(wsSource.Range("A2:CY2"), wsSource.Range("A2:CY2").End(xlDown)).SpecialCells(xlCellTypeVisible)

我遇到的问题是我无法获取源范围来选择可见的已过滤行。我尝试了上述的组合 - 当前的一个将第2行复制到目标表的每一行。我也有类似的半成功:

Set rngSource = wsSource.Range("A:CY")

正确地复制和粘贴但忽略了过滤器(即只是复制了源中的所有行)。

感谢。

1 个答案:

答案 0 :(得分:1)

仅将范围拆分为左上角和右下角的单元格,然后复制可见的单元格:

Set rngSource = wsSource.Range(wsSource.Range("A2"), 
    wsSource.Range("CY2").End(xlDown)).SpecialCells(xlCellTypeVisible)

rngSource.Copy

wsDest.Activate
rngDest.Cells(1, 1).Select
ActiveSheet.Paste

OR

Set rngSource = wsSource.Range(wsSource.Range("A2"), 
    wsSource.Range("CY2").End(xlDown))

rngSource.SpecialCells(xlCellTypeVisible).Copy

wsDest.Activate
rngDest.Cells(1, 1).Select
ActiveSheet.Paste