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. I have formulas 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 and 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With