I know exporting to csv has been asked about a billion times, and I've done it quite a few times, but I'm trying to figure out how to export only a portion of the sheet to csv without cycling through each row or cell and printing them individually to file. I need to maintain local formatting as one requirement.
Sheets("PI_OUTPUT").Copy
This copies the entire sheet, warts and all. I have formula's in rows 1 to 20000 and columns A to X, but with a variable amount of blank rows after the data has been processed. If I use the copy method I copy all the empty rows, which outputs as rows of commas. ,,,,,,, etc....
I tried using activesheet.deleterows to trim the output file after the copy, but that gives me an error.
I've tried using:
Worksheets("PI_OUTPUT").Activate
Sheets("PI_OUTPUT").Range("A2:X5000").Copy
I've tried to use another suggestion: specialcells(xlCellTypeVisible), but I can't seem to get it to work:
Set rng = Sheets("PI_OUTPUT").SpecialCells(xlCellTypeVisible)
Set Workbook = Workbooks.Add
With Workbook
Call rng.Copy
.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
.SaveAs filename:=MyPath & MyFileName, FileFormat:=xlCSV
.Close
End With
To make it worse I have to do it across a number of sheets, all with variable number of columns, rows, all saved to separate files, so I'm looking for something I can repeat a number of times. I've got a folder path pop up to select the location, and have a dynamically constructed file name, but the copy / paste evades to file me.
Currently tearing what little hair I had out after countless google searches, any help gratefully received.
You can use the code below;
Sub testexport()
'Adpated from OzGrid;
' export Macro as CSV
Dim wsh As Worksheet
Set wsh = ThisWorkbook.Worksheets("PI_OUTPUT")
With wsh.Range("A2:X20000")
.AutoFilter 1, "<>" 'Filter to get only non-blank cells
'assuming there is no blank cell within a filled row:
wsh.Range(wsh.Cells(2, 1), wsh.Cells(24, 2).End(xlDown)).Copy 'copy non-blank cells
'.AutoFilter should not cancel autofilter as it clears cutcopy mode
End With
Application.DisplayAlerts = False 'avoid "save prompt window"
Workbooks.Add
ActiveSheet.Paste
'Saves to C drive as Book2.csv
ActiveSheet.SaveAs Filename:= _
"C:\Book2.csv" _
, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
wsh.Range("A2:X20000").AutoFilter 'clear the filter
Application.DisplayAlerts = True 'set to default
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.