4

I have a csv file, for example with data as below (a.csv) to convert into Excel.

In the second column the leading 0s are truncated.

Is there a way to define the second column as text before importing the csv into Excel?

I dont want to append "`" or any characters to the second column as suggested in many solutions.

a.csv
--------
123,001232323
456,004567772

I have the code below.

srccsvfile = "C:\a.csv"
tgtxlsfile = "C:\a.xls"

'Instantiate Excel
Set objExcel = CreateObject("Excel.Application")

'open the CSV file
Set objWorkBook = objExcel.Workbooks.open(srccsvfile)

Set objWorksheet1 = objWorkbook.Worksheets(1)

objWorksheet1.Columns("A:I").AutoFit
objWorksheet1.Columns("B").NumberFormat="@"

'Save the file as excel workbook
objWorkBook.SaveAs tgtxlsfile, 39

'close workbook
objWorkBook.Close False
'quit excel
objExcel.Quit

'clean up
Set objWorkBook = Nothing
Set objExcel = Nothing
Community
  • 1
  • 1
liju mathew
  • 41
  • 1
  • 3

2 Answers2

0

Change the cell's format to 'text' rather than 'general' or 'number' and Excell will leave it alone.

Brian Willis
  • 22,768
  • 9
  • 46
  • 50
0

I am not sure where from you tried to execute your code. Here is what you could do from Excel VBA; executing the code from elsewhere would require few tweaks already mentioned in your code...

Sub importCSVFile()
Dim objWorkBook As Workbook
Dim myFile as String
srccsvfile = "C:\temp\a.csv"

Workbooks.OpenText Filename:=myFile, Origin:=-535, StartRow:=1, _
       DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter _
        :=False, Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
        Other:=True, OtherChar:=",", FieldInfo:=Array(Array(1, 1), Array(2, 2)), _
        TrailingMinusNumbers:=True

Set objWorkBook = ActiveWorkbook

'do something with active WorkBook

End Sub
salih0vicX
  • 1,363
  • 1
  • 8
  • 9