VBA错误53找不到文件

时间:2016-03-22 13:25:59

标签: excel vba

在Excel中运行以下Excel VBA时,我收到错误53消息,指出它无法找到文件?但是该文件具有确切的文件扩展名和名称。 这需要查看文本文件并将其拆分为excel中的列。但我收到错误53说明它无法找到该文件。

非常感谢任何帮助。感谢



Sub SplitTxt_01()
Const HelperFile As String = "ABCD" '<<< temp. helper text file Name
Const N As Long = 500000  '<<< split each txt in N rows, CHANGE
Dim myPath
myPath = "C:\Desktop\" '<<< folder path, CHANGE'
Dim myFile
myFile = "2015226d.txt" '<<< your text file. CHANGE txt file name as needed
Dim WB As Workbook, myWB As Workbook
Set myWB = ThisWorkbook
Dim myWS As Worksheet
Dim t As Long, r As Long
Dim myStr
Application.ScreenUpdating = False
'split text file in separate text files
myFile = Dir(myPath & myFile)
Open myPath & myFile For Input As #1
t = 1
r = 1
Do While Not EOF(1)
Line Input #1, myStr
If r > N Then
t = t + 1
r = 1
End If
Open myPath & HelperFile & t & ".txt" For Append As #2
Print #2, myStr
Close #2
r = r + 1
Loop
Close #1
'copy txt files in separate sheets
For i = t To 1 Step -1
Workbooks.OpenText Filename:=myPath & HelperFile & i & ".txt", DataType:=xlDelimited, Tab:=True
Set WB = ActiveWorkbook
Set Rng = ActiveSheet.UsedRange
Set myWS = myWB.Sheets.Add
myWS.Name = HelperFile & i
Rng.Copy myWS.Cells(1, 1)
WB.Close False
Next
myWB.Save
'Delete helper txt files
Set Fso = CreateObject("Scripting.FileSystemObject")
Set Fldr = Fso.GetFolder(myPath)
For Each Filename In Fldr.Files
If Filename Like "*" & HelperFile & "*" Then Filename.Delete
Next
Application.ScreenUpdating = True
End Sub
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

 myPath = "C:\Desktop" & "\"

 myFile = "2015226d.txt" 

这是我常见的PITA问题,因为我最终在文件夹中循环搜索很多内容。我学到了很难的方法,就像你总是导致错误一样离开\。像其中任何一个&#34;不是那里&#34;或者事情被丢弃在错误的地方。

此外,您似乎没有告诉它MyStr是什么(我只是复制/粘贴您的代码,以便您可以看到它在哪里昏暗,以及您尝试使用它的位置)

 Dim myStr
 Application.ScreenUpdating = False
 'split text file in separate text files
 myFile = Dir(myPath & myFile)
 Open myPath & myFile For Input As #1
 t = 1
 r = 1
 Do While Not EOF(1)
 Line Input #1, myStr