loosing leading zeros in excel/csv import

Hi everyone.
I have another one of those leading zero problems with excel and csv files. I currently have a script that runs and pulls in a csv file, cuts half the fields out, shottens one of the field lengths and then saves the file again. It runs automatically on an entire folder using a wildcard for the filename.
Today we had a new problem in that one of the fields started with a zero and excel removed it, which caused major plant faliure because the resulting files are combined and then read into a plc for build info.

Anyone know how to read in the csv and keep the zero?

this is the script currently used:

rivate Sub Workbook_Open()
Application.Visible = True
Dim FileName As String
           Const Folder = "C:\process"
               FileName = Dir(Folder & "\*.txt")
            Do While FileName <> ""
                Application.Workbooks.Open Folder & "\" & FileName
                    ActiveCell.FormulaR1C1 = "=MID(RC[-1],1,50)"
                    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                        :=False, Transpose:=False
                    Application.CutCopyMode = False
                ActiveWorkbook.Close True
                FileName = Dir
End Sub

any help appreciated.
Who is Participating?
RobSampsonConnect With a Mentor Commented:
I have tried your solution of saving the sample data to a CSV file.
It seems that you cannot get it to work with a CSV extension, because Excel treats them differently.  If you change it to a TXT extension, when you open it in Excel, you get the Text File Import wizard, which allows you to select a) the field delimiting character, and b) the field data type.
Therefore, if you programmatically change the extension to a TXT through:
objFSO.CopyFile strCSVFile, strTXTFile, True
Then you can use this to open the text file in TEXT field format, which keeps the zeros.
Const xlDelimited = 1
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.OpenText _
    strFileOutputPath,,,xlDelimited,,,False,False,True,,,,Array(Array(1, 2), Array(2, 2), Array(3, 2))

Then probably just delete the TXTfile with:
objFSO.DeleteFile strTXTFile, True

Hope that helps,

Can we have a look at a few lines of the csv file where the zero gets stripped?

Basically what is going in and what is coming out.  A few lines will do - we don't need all the data.
Aidy_BAuthor Commented:
yep, here is the file before opening with excel, and the 'rev1' version is after saving as csv in excel.
Even when only just opened for the first time in excel, i cannot retrieve the leading zero using any change in ormatting for that column.

i will postr the links when i get home later when i can ftp the files up somewhere

Thanks, Aidy.
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Aidy_BAuthor Commented:
ok, didnt get round to ftp'ing the files up somewhere last night so thought i would suggest a different approach.

I have tried this and it produces exactly the same issues so will demonstrate what i am going on about.

Open notepad and copy/paste the following line:


then save it as a csv with the filename '09073641.csv'

(Although i acknowledge most of the above details dont have to be as shown to simulate the problem, it will keeps everyones tests identical)

now when that file is double clicked, or open by selecting 'Open using Excel', the leading zero in the first 2 field has gone, and no amount of re-formatting at that point will bring them back. So regardless of how the file is then saved, i need to find out how to change the formating of the fields before it opens the file and removes the zeros. as you can see from the script, this is an automated process which works its way through an entire directory of files and as such, any solution needs to be compatible with this method of working.

Use xstarter
Usually Excel does it's own formatting based on a Cell Format.
You could try setting the Cell format to Text before / as / after you edit it.
Try something like:
   Selction.NumberFormat = "@"
This should stop Excel from autoformatting the contents.
Also try opening the csv file in Notepad after it is saved, before you open it again in Excel, and
you will have a better idea of whether the zeros are stripped as it is saved, or after it is re-opened.


FYI, it is the 2 as the second parameter in the Arrays that specifies the Text data type.  If the second value was a 1, it would be "general" which would remove leading zeros.  If it were 3, that's a date format, etc, etc.

Aidy, I hope my previous post has helped you.  The solution worked for me while testing.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.