Semi colon seperated csv in VBA - excel

I am creating a csv as semi colon seperated, but the file output of csv has a blank line at top.
Please help me what needs to update in my below code
Sub WriteToCSV()
Dim FileNumber As Long
Dim temp As String
Dim cl As Range
Dim rw As Range
FileNumber = FreeFile '
'get a new file number
FileNumber = FreeFile
' change path & file name as required
Open "C:\Users\standard\Desktop\automation\ankur.csv" For Output As #FileNumber
Print #FileNumber, temp
'change the worksheet index by its real position or Name between quotes, eg Worksheets("Sheet1").
For Each rw In Worksheets(1).Range("A1").CurrentRegion.Rows
For Each cl In rw.Cells
temp = temp & cl.Value & ";"
Next cl
Print #FileNumber, temp
're=initialise string
temp = ""
Next rw
Close #FileNumber
End Sub

Your code has Print #FileNumber, temp immediately after opening the file for output. As temp has not been set to anything, it is an empty string, hence the blank line.
Also, you don't need to use FreeFile twice.
Regards,

Related

While exporting/converting to CSV, replace first line with newline

EDIT: I CHANGED THIS ORIGINAL POST SO I COULD EMBED THE FINAL CODE I WENT WITH.
Using the code at the bottom to export a specific worksheet and convert to a CSV file.
The output file will consistently have the very first line beginning with a blank space followed by the string
,,Primary,Secondary,Tertiary
I would like to remove/replace that line with a newline. i.e..
CURRENT:
,,Primary,Secondary,Tertiary
100,106,2165483624,2165483624,8133181331
I would like to remove/replace that top line with a newline. i.e:
(newline here)
100,106,2165483624,2165483624,8133181331
That line will always be the first line, and will be the only line beginning with a space and two commas, also the only one with the words Primary,Secondary,Tertiary comma-delimited.
I've spent several hours checking this site and others but either
I'm using the wrong keywords or my desired outcome hasn't been
documented yet. Thanks in advance.
CODE I ENDED UP USING IS BELOW
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

Excel VBA extra Newline getting inserted through print statement

Through a Excel VBA macro, I'm trying to print up to 10 space seperated arguments for a selected range in excel.
For example, I have the 24 values in my selection range A1:A24 - (say Val1, Val2, Val3, Val4, etc.)
Using the following VBA code, I want to get the output in the "outfile.bat" as
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" Val1 Val2.... Val10
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" Val11 Val2.... Val20
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" Val21 Val22 Val23 Val24
i.e. each line should get printed with maximum of 10 argument values (seperated by a space). Anything above that should be moved to next line (again max of 10 space seperated arguments)
Somehow, the following code is
(1) NOT keeping the output to the same line and
(2) Inserts a newline at the 10th value, but not at the 20th, 30th and other values.
It produces the following:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Val1
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Val2
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Val3
and so on....
Here is my code:
Private Sub GetChromeFile_Click()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer, a As Integer
myFile = "C:\Users\User1\" & "outfile.bat"
Set rng = Selection
Open myFile For Output As #7
a = 0
For i = 1 To rng.Rows.Count
Print #7, Chr(34) & "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & Chr(34)
a = a + 1
cellValue = rng.Cells(i).Value
If (a = 10) Then
Print #7, " " & cellValue & vbNewLine
Else
Print #7, " " & cellValue
End If
Next i
Close #7
Range("F5").Value = " Done!"
End Sub
Please let me know where this may be going wrong.
Thanks
The print statement prints a line to the file, so adding vbNewLine at the end of each is redundant. You're also making calls to Print for each argument value (cellValue in your code), which is why those are appearing on their own line.
You can most likely construct the entire file contents as a single string, and then use a single Print statement to write the whole file. If you're dealing with an enormous amount of data, you may need to segment it but for most cases this should work:
Option Explicit
Sub writebat()
Const pathTxt$ = """C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" "
Dim lineTxt As String
Dim cellValue As String
Dim fname As String
Dim ff As Long
Dim a As Long
Dim i As Long
Dim rng As Range
Set rng = Selection ' Range("A1:A37")
fname = "C:\Users\User1\" & "outfile.bat" ' "C:\debug\output.txt"
ff = FreeFile()
Open fname For Output As #ff
lineTxt = pathTxt
a = 1
For i = 1 To rng.Rows.Count
'## Add the cell value to the string
lineTxt = lineTxt & rng.Cells(i).Value & " "
If a Mod 10 = 0 Then
'## Start a new line with the executable path
lineTxt = lineTxt & vbNewLine & pathTxt
End If
a = a + 1
Next
Print #ff, lineTxt
Close #ff
End Sub
This yields the following output:

Trying to export a range in Excel to CSV with only cells that contain data

Good afternoon all,
I am building an excel sheet for my coworkers to use to generate CSV files. I need to get an output with header row and then all the data from the sheet. It will be no more than 40 rows, but could be less rows. I currently have a lot of formulas in the sheet doing the heavy lifting for my coworkers on things like generating usernames/etc from the input data. I need to have them click a button and get the CSV file on the other end. My current issues are as follows.
1.) my CSV contains double quotes on every field, even though commas should not be in the input data. I need to prevent this as the program we are feeding these csv files to does not like the double quotes AT ALL. Yes, I know you can open it in notepad and replace all to remove them but im trying to build a one click solution as some of the folks using this are not very tech savvy.
2.) my macro is exporting all forty rows of data currently. I need it to only export the rows that contain data. Theoretically with the formulas built there should be no "partial" rows, only a full row or a blank row.
3.) When generating the CSV file its not appending a filetype at all, I need it to specify a .txt. filetype if at all possible as again, the program we are feeding these to is very picky.
Sub CommandButton1_Click()
Dim filename As String
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
filename = InputBox("Please enter file name", "Save as CSV", "CSV_" & Format(Now, "DD_MM_yyyy"))
myFile = Application.DefaultFilePath & filename
Set rng = Range("A1:J41")
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End Sub
This is what your code would have to look like. Unfortunately I wasn't able to get rid of the double quotes, maybe someone else has an idea for that.
Sub csvExport()
Dim filename As String
Dim myFile As String, cellValue As Variant, i As Integer, j As Integer
Dim ws As Worksheet
filename = "\" & InputBox("Please enter file name", "Save as CSV", "CSV_" & Format(Now, "DD_MM_yyyy")) & ".txt"
myFile = Application.DefaultFilePath & filename
Set ws = Worksheets("YOURSHEETNAME")
With ws
Open myFile For Output As #1
For i = 1 To .UsedRange.Rows.Count
For j = 1 To .UsedRange.Columns.Count
cellValue = .Cells(i, j).Value
If j = .UsedRange.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End With
End Sub

Import a txt file into excel and format with text to column

I am attempting to import a .txt file into Excel via VBA code and then format the content with a text to column command.
The txt file holds content in the following:
DATE | 1 | 2 | 3 | 4 | Something ||||| Not Sure |||||
DATE | 5 | 6 | 7 | 8 | New ||||| Whatever |||||
Currently, using code I've found and slammed together, I've managed to get this far
Sub Sample()
Dim MyData As String, strData() As String, myFile As String
myFile = Application.GetOpenFilename()
Open myFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, "|")
End Sub
This merely gets all of the data from the txt file and separates each item into an array.
I'd like to put the items from the array into columns of excel starting from Range("A5") AND account for each new row.
Help?
(Edit: I thought of moving down a row anytime I get to a empty array selection, but there are many blanks within each row and this wouldn't work. Also, the lengths of the rows are inconsistent depending on content.)
You need to Split the data two ways: into lines using the NewLine character, then into cells using |
Note that the line break chacter in your text file may not be vbNewLine. If this code doesn't split into lines, thats the first place to look.
To complete your code as poseted, try
Sub Sample()
Dim MyData As String
Dim lineData() As String, strData() As String, myFile As String
Dim i As Long, rng As Range
' lets make it a little bit easier for the user
myFile = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Open myFile For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
' Split into wholes line
lineData() = Split(MyData, vbNewLine)
Set rng = Range("A5")
' For each line
For i = 0 To UBound(lineData)
' Split the line
strData = Split(lineData(i), "|")
' Write to the sheet
rng.Offset(i, 0).Resize(1, UBound(strData) + 1) = strData
Next
End Sub
As an alternative, treat the .txt file as, well, Text
Sub Sample()
Dim fn As Integer
Dim MyData As String
Dim lineData As String, strData() As String, myFile As String
Dim i As Long, rng As Range
myFile = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Set rng = Range("A5")
' Lets not rely on Magic Numbers
fn = FreeFile
Open myFile For Input As #fn
i = 1
Do While Not EOF(fn)
Line Input #fn, lineData
strData = Split(lineData, "|")
rng.Cells(i, 1).Resize(1, UBound(strData) + 1) = strData
i = i + 1
Loop
Close #fn
End Sub

Google Docs Export CSV with double quotes

I have a Google spreadsheet that I need to export and have every field contained in double quotes "field" but at the moment it doesn't not do this.
Is there an easy way to achieve this without resorting to manually editing hundreds of lines?
Max
You can use from excel too using appropiate macro like this:
Sub QuoteCommaExport()
' Dimension all variables.
Dim DestFile As String
Dim FileNum As Integer
Dim ColumnCount As Integer
Dim RowCount As Integer
' Prompt user for destination file name.
DestFile = InputBox("Enter the destination filename" & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
' Obtain next free file handle number.
FileNum = FreeFile()
' Turn error checking off.
On Error Resume Next
' Attempt to open destination file for output.
Open DestFile For Output As #FileNum
' If an error occurs report it and end.
If Err <> 0 Then
MsgBox "Cannot open filename " & DestFile
End
End If
' Turn error checking on.
On Error GoTo 0
' Loop for each row in selection.
For RowCount = 1 To Selection.Rows.Count
' Loop for each column in selection.
For ColumnCount = 1 To Selection.Columns.Count
' Write current cell's text to file with quotation marks.
Print #FileNum, """" & Selection.Cells(RowCount, ColumnCount).Text & """";
' Check if cell is in last column.
If ColumnCount = Selection.Columns.Count Then
' If so, then write a blank line.
Print #FileNum,
Else
' Otherwise, write a comma.
Print #FileNum, ";";
End If
' Start next iteration of ColumnCount loop.
Next ColumnCount
' Start next iteration of RowCount loop.
Next RowCount
' Close destination file.
Close #FileNum
End Sub
I found that you can achieve this by using Open Office. From their you can define your own separators and surrounding characters.
When saving/exporting as a CSV check the box saying define my own characters.

Resources