当我尝试打开CSV文件时,我得到:
错误53:找不到文件
我在第4行收到错误Open FilePath For Input As #1
我究竟做错了什么?
这是我第一次打开CSV,请放纵我的代码。
Sub opentextfile()
Dim FilePath As String
FilePath = "/Users/christinekelly/Desktop/authors.csv"
file1 = FreeFile
Open FilePath For Input As #file1
row_number = 0
Do Until EOF(1)
Line Input #file1, LineFromFile
LineItems = Split(LineFromFile, ",")
ActiveCell.Offset(row_number, 0).Value = LineItems(2)
ActiveCell.Offset(row_number, 1).Value = LineItems(1)
ActiveCell.Offset(row_number, 2).Value = LineItems(0)
Number = row_number + 1
Loop
Close #file1
End Sub
答案 0 :(得分:1)
所以从查看@ Rebekare对此question的答案来看,这对我有用。
我转到问题文件test.csv
并打开了即时窗口并输入了?ThisWorkbook.Path
并获得了HDD:Users:USER:Desktop
。
然后,我使用Application.PathSeparator
&的建议连接这条路径。文件名即
FilePath = "HDD:Users:USER:Desktop" & Application.PathSeparator & "test.csv"
这是一种有用的方法,因为您获得了实际的文件路径语法,然后将路径分隔符决定权交给Application
。
根据@Mat' sMug的建议,我找到this,打开文件对话框,然后选择你想要完整路径的文件,并通过消息框返回。
Sub PathofFile()
OpenFile = Application.GetOpenFilename()
MsgBox OpenFile
End Sub
在同一个链接中建议使用Dir
函数来测试文件路径是否有效。如果有效,则返回文件名,否则会出现错误,您可以使用该错误确定下一个操作,例如:以下返回" test.csv"如果它存在于该文件路径中。
MsgBox Dir("HDD:Users:USER:Desktop:test.csv")
如果您正在对该文件执行其他操作,则可能需要使用Microsoft的IsFileOpen函数添加测试以查看该文件是否先打开。示例如下:
Sub Test
If Not IsFileOpen(FilePath) Then
Set wb = Workbooks.Open(FilePath)
End If
End Sub
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function