Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


loosing leading zeros in excel/csv import

Posted on 2007-03-19
Medium Priority
Last Modified: 2013-11-25
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.
Question by:Aidy_B
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 11

Expert Comment

ID: 18754285
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.

Author Comment

ID: 18757825
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.

Author Comment

ID: 18762430
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.


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.


Expert Comment

ID: 18806490
Use xstarter
LVL 65

Expert Comment

ID: 18895241
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.


LVL 65

Accepted Solution

RobSampson earned 2000 total points
ID: 18956137
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,

LVL 65

Expert Comment

ID: 18956141
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.

LVL 65

Expert Comment

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


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question