I’ve come across a nasty little bug in Excel VBA’s
.OpenText method.. It errors on opening any text or CSV file when the first two letters are upper-case “ID”. Here is the article from MS so you know I’m not crazy: http://support.microsoft.com/kb/323626
So, I’m trying to figure out a workaround that does NOT involve copying the entire file just to re-name the first header. I am working with some large text files and this would be an unsatisfactory last resort.
On Error Resume Next before the
.OpenText call but that didn’t work.. Has anybody come across this and found a simple solution I’m missing? Is there a way to just crack open the first line and find/replace inside of a text file? Or extra parameters to
.OpenText I could use?
I wrote this for you. Just call it passing the filepath prior to attempting to open it. I deliberately wrote this with late binding, so no references are required. it will add an apostrophe to the beginning of the file, if the file starts with “ID”.
Sub FixIDProblem(filePath As String) Dim fso As Object Dim text As Object Dim contents as String Set fso = CreateObject("Scripting.FileSystemObject") If fso.FileExists(filePath) Then 'Open the file for reading Set text = fso.OpenTextFile(filePath, 1) 'Load the text contents to variable contents = text.ReadAll 'Check for the forbidden text at the beginning If Left(contents, 2) = "ID" Then text.Close 'Overwrite textfile with it's contents plus an apostraphe Set text = fso.OpenTextFile(filePath, 2) text.Write "'" & contents End If text.Close Else MsgBox "File does not exist" End If Set fso = Nothing End Sub
Just turn the alerts off:
Application.DisplayAlerts = False Application.Workbooks.OpenText Filename:="startwithID.tab" Application.DisplayAlerts = True
I did this instead :
Application.DisplayAlerts = False On Error Resume Next Workbooks.OpenText Filename:=myfile, DataType:=xlDelimited, Tab:=False, Semicolon:=True, Local:=True Workbooks.OpenText Filename:=myfile, DataType:=xlDelimited, Tab:=False, Semicolon:=True, Local:=True Application.DisplayAlerts = True
The first OpenText fails, but the second one works.
The FixIDProblem is a good idea but fails on big files (~ 40MB)