loosing leading zeros in excel/csv import

Posted on 2007-03-19
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.

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now


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 500 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

Independent Software Vendors: 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

If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
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…
Suggested Courses
Course of the Month6 days, 10 hours left to enroll

634 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