如何在VBA中使用.OpenText打开文本文件,该文件以“ID”之类的第一列开始,而不会出现SYLK错误

我在Excel VBA的.OpenText方法中遇到了一个令人讨厌的小错误。当前两个字母是大写“ID”时,打开任何文本或CSV文件时出错。 这里是来自MS的文章,所以你知道我不疯狂: http : //support.microsoft.com/kb/323626

所以,我试图找出一个解决方法,不涉及复制整个文件只是为了重命名第一个头。 我正在处理一些大的文本文件,这将是一个不尽人意的最后的手段。

我已经尝试On Error Resume Next .OpenText调用之前的On Error Resume Next ,但没有工作..有没有人遇到这个,find了一个简单的解决scheme,我失踪了? 有没有办法只是打开第一行,并find/replace文本文件内? 或者额外的参数.OpenText我可以使用?

我为你写了这个。 在尝试打开文件path之前,先调用它传递文件path。 我故意写了这个后期绑定,所以不需要参考。 如果文件以“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 

只要closures警报:

 Application.DisplayAlerts = False Application.Workbooks.OpenText Filename:="startwithID.tab" Application.DisplayAlerts = True 

我做了这个,而不是:

 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 

第一个OpenText失败,但第二个工作。

FixIDProblem是一个好主意,但在大文件上失败(〜40MB)