OK a new and even better method than the macro:
Open a text editor and paste in this script. And save it as a .ps1 file.
enquote-csv.ps1
Code:
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$path,
[Parameter(Mandatory = $false, Position = 1)]
[string]$output
)
if($path -AND (Test-Path $path))
{
if(!$output)
{
$output = $path
}
$csv = Get-Content $path
#column headers shouldn't be quoted so written as-is to output file
Set-Content -Path $output -Value $csv[0]
#skip first line of csv file
for($i = 1; $i -lt $csv.length; $i++)
{
$fields = $csv[$i].Split(',')
for($j = 0; $j -lt $fields.length; $j++)
{
$fields[$j] = '"' + $fields[$j] + '"'
}
Add-Content -Path $output -Value ([string]::Join(',',$fields))
}
}
Save your Excel document as a .csv.
Open PowerShell and run the above script as follows:
This line of code will replace the file.csv with enquoted fields
Code:
C:\scripts\enquote-csv.ps1 'C:\path to\file.csv'
This line of code will enquote the fields and save the output to the path specified
Code:
C:\scripts\enquote-csv.ps1 'C:\path to\file.csv' 'C:\path to\new file.csv'
Voila!
Macro Method
Just in case you would rather do it the slightly harder way!
Create a new macro in excel and paste in the following [remove any existing code in the editing window]:
Code:
Sub AddQuote()
Dim myCell As Range
For Each myCell In Selection
If myCell.Value <> "" Then
myCell.Value = Chr(34) & myCell.Value & Chr(34)
End If
Next myCell
End Sub
Save your workbook as .xslm
Select all the cells you wish to be quoted then run your macro.
Save the document as a .csv. Open the CSV in a regular text editor [notepad, notepad++, et al.]
Do a search and replace. Search for
""" and replace with
"
Save the changes.
Excel ignores quotes around a text string, so when saving as CSV it uses """ to display the quote. Excel normally
gets rid of the surrounding quotes, but other applications may be confused by them all.
This method gets rid of the need for creating two extra columns and doing a search and replace on multiple strings.
EDIT:
Rather than using a text editor for the string replacement, you could also use PowerShell to do it for you:
Code:
(get-content 'C:\path to\file.csv') | % { $_ -replace '"""', '"' } | set-content 'C:\path to\file.csv'
You can save the above into a script if you don't want to type it each time! Also, if you wish to keep the original CSV, change the path after set-content to something else.