prepend character to text file

supmktg

Registered User.
Local time
Today, 12:18
Joined
Mar 25, 2002
Messages
360
I am importing data from csv, txt or xls files. I allow the user to view the file in Excel before import using Application.FollowHyperlink.

If the text in cell A1 begins with "ID" the file won't open because Excel mistakes it for a SYLK file. I can work around that issue by changing the text in cell A1 before it is opened by Excel.

I have cobbled together the following code that will read the file and if the first 2 characters are "ID" then it will write an "R" at the beggining of the file:

Code:
Sub ReadWriteFile(strFile As String)
Dim hFile As Long
Dim strData As String * 2

hFile = FreeFile
'strFile = "C:\Something.txt"
Open strFile For Binary Access Read As hFile Len = 2
Get hFile, 1, strData
Close hFile

If strData = "ID" Then
Open strFile For Binary Access Write As hFile Len = 2
Put hFile, , "R"
Close hFile
End If

End Sub

What I want to do is prepend the "R" so cell A1 = "RID". This code is changing "ID" to "RD". Can someone point out where my code is failing?

Thanks,
Sup
 
I am importing data from csv, txt or xls files. I allow the user to view the file in Excel before import using Application.FollowHyperlink.

If the text in cell A1 begins with "ID" the file won't open because Excel mistakes it for a SYLK file. I can work around that issue by changing the text in cell A1 before it is opened by Excel.

I have cobbled together the following code that will read the file and if the first 2 characters are "ID" then it will write an "R" at the beggining of the file:

Code:
Sub ReadWriteFile(strFile As String)
Dim hFile As Long
Dim strData As String * 2

hFile = FreeFile
'strFile = "C:\Something.txt"
Open strFile For Binary Access Read As hFile Len = 2
Get hFile, 1, strData
Close hFile

If strData = "ID" Then
Open strFile For Binary Access Write As hFile Len = 2
Put hFile, , "R"
Close hFile
End If

End Sub
What I want to do is prepend the "R" so cell A1 = "RID". This code is changing "ID" to "RD". Can someone point out where my code is failing?

Thanks,
Sup

Have you tried:
Open strFile For Binary Access Write As hFile Len = 3
Put hFile, , "RID"
 
I think if you write to a file with the tools you're talking about you either append data or overwrite data. To prepend data, I expect you need to read the whole file into a variable, say strOldFile, prepend your data, like ...
Code:
strNewFile = "R" & strOldFile
... and the re-write the entire file ...
Code:
file.write strNewFile
I don't believe you can insert a character at the beginning of a file and expect that all the existing characters will shift one position to the right.
 

Users who are viewing this thread

Back
Top Bottom