Give multiple worksheets in workbook, export specific worksheet (CSV) while
converting to CSV file, removing column header and adding an empty line at the beginning.
Using this code right now, which exports the active worksheet, does the conversion,
etc, but in this case, I have to be in the CSV worksheet for it to function properly.
I'd like to export CSV automatically without needing to be in.
I tried setting a few variables and exporting but obviously Im still too much
of a novice.
UPDATE: After multiple hours of research and testing, most of which gave me various fun errors, I found the solution and added a line just below the Sub identifier and above the Private Sub
Sub auto_export_CSV()
'set CSV as active worksheet for export
Sheets("CSV").Activate
'Private Sub btn_Export_to_CSV_Click()
Dim csvFilePath As String
Dim fileNo As Integer
Dim fileName As String
Dim oneLine As String
Dim lastRow, lastCol As Long
Dim idxRow, idxCol As Long
' --- get this file name (without extension)
fileName = Left(ActiveWorkbook.Name, InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) - 1)
' --- create file name of CSV file (with full path)
csvFilePath = ActiveWorkbook.Path & "\" & fileName & ".csv"
' --- get last row and last column
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
' --- open CSC file
fileNo = FreeFile
Open csvFilePath For Output As #fileNo
Print #fileNo, "" ' -- write one blank line
' --- row loop
For idxRow = 2 To lastRow
oneLine = ""
' --- column loop: concatenate oneLine
For idxCol = 1 To lastCol
If (idxCol = 1) Then
oneLine = Cells(idxRow, idxCol).Value
Else
oneLine = oneLine & "," & Cells(idxRow, idxCol).Value
End If
Next
' --- write oneLine > CSV file
Print #fileNo, oneLine ' -- Print: no quotation (output oneLine as it is)
Next
' --- close file
Close #fileNo
MsgBox "CSV file completed !!" & Chr(13) & csvFilePath
End Sub
Moderator's note: Please take the time to review our rules. There aren't many, and they are all important. Rule #3 requires code tags. I have added them for you this time because you are a new member. --6StringJazzer
Bookmarks