CSV text data altered on file open
Use this code to read the CSV data. Before running the macro format the
cells to the correct format. The code will not change the format when the
data is read.
Sub GetCSVData()
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Const Delimiter = ","
Set fsread = CreateObject("Scripting.FileSystemObject")
'default folder
Folder = "C:\temp\test"
ChDir (Folder)
FName = Application.GetOpenFilename("CSV (*.csv),*.csv")
RowCount = LastRow + 1
If FName < "" Then
'open files
Set fread = fsread.GetFile(FName)
Set tsread = fread.OpenAsTextStream(ForReading, TristateUseDefault)
Do While tsread.atendofstream = False
InputLine = tsread.ReadLine
'extract comma seperated data
ColumnCount = 1
Do While InputLine < ""
DelimiterPosition = InStr(InputLine, Delimiter)
If DelimiterPosition 0 Then
Data = Trim(Left(InputLine, DelimiterPosition - 1))
InputLine = Mid(InputLine, DelimiterPosition + 1)
Else
Data = Trim(InputLine)
InputLine = ""
End If
Cells(RowCount, ColumnCount) = Data
ColumnCount = ColumnCount + 1
Loop
RowCount = RowCount + 1
Loop
tsread.Close
End If
End Sub
"Mike P" wrote:
I am opening a CSV file in which the first column is a text field. The text
field contains a 9 digit alpha numeric characters. Excel makes the
assumption that the field is a number, which then alters the content of the
alpha numeric text data by removing all leading zeros and if the letter "E"
or "e" exists in the text field, Excel turns it into Scientific notation.
After I open the file, I select the cell, then set format to text, but it is
too late. The scientific notation is set and all leading zeros are gone.
Is there a way to not have this happen? I am using Excel 2007
Thanks in advance for your help!
|