Google Docs Export CSV with double quotes - excel

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.

Related

Semi colon seperated csv in VBA

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,

Export excel rows to individual text files

I'm using the VBA code below to export Excel rows to individual text file (file name is Column B)
Sub ExportTextFiles()
Dim i As Long
Dim LastDataRow As Long
Dim MyFile As String
Dim fnum
LastDataRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To LastDataRow
'The next line uses the contents of column B on the same row to name it
MyFile = "C:\test\" & ActiveSheet.Range("B" & i).Value & ".txt"
fnum = FreeFile()
Open MyFile For Output As fnum
Print #fnum, Format(Range("A" & i))
Close fnum
Next i
End Sub
My problem is only 255 Characters of row exported in the text.
is there a workaround ?
For reasons that I have not been able to find clear documentation, when you use the Format function with no format defined, it will return only 255 characters.
I don't understand why you need to use the Format function in your Print statement, but if you remove it, the 255 character limitation seems to disappear.
The only thing I think you might have to worry about is the cell contents limitation of 32,767 characters.

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

Export Excel stylesheet to CSV with comma separated and cells with text format in double quotes

Example - Source:
ID NAME TEXT
01 John Lore ipsum..
In this case all cells have format General and Lore ipsum.. text have format Text
And I want export this excel stylesheet to csv with comma separated and lore ipsum.. text with double quotes, something like this:
ID,NAME,TEXT
01,John,"Lore ipsum.."
Might not be exactly as asked, however this is what worked best for me:
Save the CSV in Excel normally (File > Save As > CSV (Comma separated))
Open a powershell window where the exported CSV is
Run this command (considering the CSV file was named "Book1.csv":
import-csv -path .\Book1.csv -Delimiter ";" | export-csv -path .\Book1_comma.csv -Delimiter ","
The following Microsoft article details the procedure you're looking for; http://support.microsoft.com/kb/291296 In the spirit of SO, I'll summarise here.
In Excel (I'm using 2003), navigate to Tools > Macro > Visual Basic Editor. That will launch the editor in a new window.
Next you want Insert > Module. In that window, paste the VB code, as follows:
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
Next you'll need to highlight the cells in your spreadsheet that you want to export. Once they've been selected, Run your macro against them. Specify a path to save your file to, and you're done.
Full credits to the author of the article at Microsoft, http://support.microsoft.com/kb/291296.

VBA Excel - Faster Execute - Copy Sheet (with charts/objects) from closed file

I am hoping to find a way to help this code run faster; so this is the path im following to try and achieve this -
current time - 23 seconds, most of it opening & closing files.
So I am attempting to pull data from files without opening them.
I've seen Microsoft.ACE.OLEDB.12.0 but I have not idea how to use it to get the entire sheet, warts and all.
I've seen a lot of solutions that pull data from cells and gets sheet names -
I want my entire sheet, all objects on that sheet, its headers, footers, everything.
This is the macro I'd like to apply it to:
Sub DirPDF_Long_Sections(LongFolderPath As String)
' ####################################################################################
' # INTRO
'-------------------------------------------------------------------------------------
' Purpose
' This procedure assists the user to put all long sections from a folder into one
' PDF file. This makes it convieniet to share the long sections & print them.
'
' THIS PROCEDURE USES DIR instead of FSO
'
' ####################################################################################
' # DECLAIRATIONS
'-------------------------------------------------------------------------------------
' OBJECTS
Dim LongFolder As String
Dim LongFile As String
Dim OpenLong As Workbook
Dim ExportWB As Workbook
'Dim FileSystemObj As New FileSystemObject
'-------------------------------------------------------------------------------------
' VARIABLES
Dim count As Long
Dim DefaultPrinter As String
Dim DefaultSheets As Variant
Dim FirstSpace As Long
Dim LastSpace As Long
Dim start_time, end_time
' ####################################################################################
' # PROCEDURE CODE
'-------------------------------------------------------------------------------------
' optimise speed
start_time = Now()
Application.ScreenUpdating = False
'-------------------------------------------------------------------------------------
' Print the Files in the Folder:
DefaultSheets = Application.SheetsInNewWorkbook '// save default setting
Application.SheetsInNewWorkbook = 1 '// create a one worksheet workbook
Set ExportWB = Workbooks.Add
Application.SheetsInNewWorkbook = DefaultSheets '// re-set application to default
LongFile = Dir(LongFolderPath & "\*PipeLongSec*", vbNormal)
While LongFile <> vbNullString '// loop through all the files in the folder
FirstSpace = InStr(1, LongFile, " ") '// record position of first space character
LastSpace = InStr(FirstSpace + 1, LongFile, " ") '// record position of last space character
Set OpenLong = Workbooks.Open(LongFile) '// open the file
OpenLong.Sheets("Long Sections").Copy After:=ExportWB.Sheets(ExportWB.Sheets.count)
'// copy sheet into export workbook
ExportWB.Sheets(ExportWB.Sheets.count).Name = Mid(LongFile, FirstSpace + 1, LastSpace - FirstSpace - 1)
'// rename sheet we just moved to its pipe number
OpenLong.Close '// close the file
LongFile = Dir() '// get next file
Wend
'-------------------------------------------------------------------------------------
' Delete the other worksheet in the temporary workbook
Application.DisplayAlerts = False
ExportWB.Sheets("Sheet1").Delete
Application.DisplayAlerts = True
'-------------------------------------------------------------------------------------
' Send Workbook to PDF - in save location
ExportWB.ExportAsFixedFormat xlTypePDF, LongFolderPath & "\" & "LongSectionCollection " & Replace(Date, "/", "-")
ExportWB.Close SaveChanges:=False
'#####################################################################################
'# END PROCEDURE
Application.ScreenUpdating = True
Set OpenLong = Nothing
end_time = Now()
MsgBox (DateDiff("s", start_time, end_time))
End Sub
Add Option Explicit before any code at the top
Convert DefaultSheets to CLngPtr(DefaultSheets)
Convert Long data types to CLngPtr(variable)
Convert to CDate(Start_Time)
Convert to CDate(End_Time)
No worries. They should be defined in the dim statement if they would remain the same data type. If this data type changes throughout the code then use as variant in the dim statement and use the conversion functions found in the object browser to convert the data types as needed.

Resources