如何将可见单元格(FILTERED TABLE CELLS)复制并粘贴到CSV

我想复制和粘贴从一个Excel到另一个使用复制和粘贴可见的单元格,因为我有一个设置范围之间的过滤表。

我想通过保存CSV来做到这一点,但显然这是不可能的。 下面的代码工作,但它似乎并不像我想要复制粘贴可见的单元格/过滤的单元格。

提前致谢。 或者,如果还有另一种推荐的方式来获取过滤表格到CSV我很想听听如何。 干杯。

Sub Macro2() ' ' Macro2 Macro ' ' Dim lastRow As Long Dim ws As Worksheet, tbl As ListObject Set ws = Sheets("Sheet1") Set tbl = ws.ListObjects("Table1") With tbl.ListColumns(3).Range lastRow = .Find(What:="*", _ After:=.Cells(1), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row End With Sheet1.Range("A2").SpecialCells(xlCellTypeVisible).Copy _ Destination:=Range("A2") ActiveWorkbook.SaveAs Filename:="C:\Users\teaz\Videos\CSV", FileFormat:= _ xlCSV, CreateBackup:=False ActiveWorkbook.SaveCopyAs Filename:="C:\Users\teaz\Videos" & Test1Str & " " & TestStr & " " & ActiveWorkbook.Name Application.ActiveWindow.Close SaveChanges:=False ActiveWorkbook.Close SaveChanges:=False End Sub 

将所有以前过滤的数据从所有工作表复制到另一个

 Sub CopyFilteredDataToNewWorkbook() Dim newBook As Excel.Workbook Dim rng As Excel.Range Dim sht As Excel.Worksheet Dim rowoffsetcount As Long Dim newsht As Excel.Worksheet Set newBook = Workbooks.Add ' ThisWorkbook.Worksheets is the same as the Sheets or Worksheets object, but more explicit For Each sht In ThisWorkbook.Worksheets ' Get the used rows and columns Set rng = sht.UsedRange ' Offset the range so it starts at row 15 rowoffsetcount = 15 - rng.Row Set rng = rng.Offset(rowoffsetcount) ' Check there will be something to copy If (rng.Rows.Count - rowoffsetcount > 0) Then ' Reduce the number of rows in the range so it ends at the same row Set rng = rng.Resize(rng.Rows.Count - rowoffsetcount) ' Check that there is a sheet we can copy it to On Error Resume Next Set newsht = Nothing Set newsht = newBook.Worksheets(sht.Index) On Error GoTo 0 ' We have run out of sheets, add another at the end If (newsht Is Nothing) Then Set newsht = newBook.Sheets.Add(, newBook.Worksheets(newBook.Worksheets.Count)) End If ' Give it the same name newsht.Name = sht.Name ' Get the range of visible (ie unfiltered) rows ' (can't do this before the range resize as that doesn't work on disjoint ranges) Set rng = rng.SpecialCells(xlCellTypeVisible) ' Paste the visible data into the new sheet rng.Copy newsht.Range("A1") End If Next End Sub 

我认为这一行是你的问题:

 '/* you only worked on Range("A2") */ Sheet1.Range("A2").SpecialCells(xlCellTypeVisible).Copy 

你应该像访问你的tbl对象:

 '/* this will give you the entire filtered table body */ tbl.DataBodyRange.SpecialCells(xlCellTypeVisible).Copy 

同样,您可以使用:

 Sheet1.Range("YourTableName").SpecialCells(xlCellTypeVisible).Copy 

最后,避免使用Active前缀的所有对象(例如ActiveWorkbookActiveWindow )。 你已经知道如何分配variables,然后保持一致。