VBA script always returns Input past end of file error

早过忘川 提交于 2020-01-05 08:15:37

问题


I have a csv file as such:

hello,world,this
is,an,example,
of,the,csv,file

The first column will always be unique.

I am getting the user to enter a string which matches an item in the first column, and the script returns the whole line:

Open "C:\file1.csv" For Input As #file_number
Do While (EOF(1) Or found = False)
    Line Input #file_number, raw_line
    pos = InStr(raw_line, fireName)
    If pos = Not 0 Then
        strData() = Split(raw_line, ",")
        found = True
    End If
Loop
Close #file_number
If found = False Then
    MsgBox "Could not find it"
    Exit Sub
End If
'REST OF THE CODE

But it always sends the message "could not find it" and exits. By default, found is a boolean value and is false.

I know it can detect the file as when I changed the read file name, it created a new one (as it does not exist).

EDIT: I changed the And to an Or and now I get the error: Run-time error 62: input past end of file


回答1:


It looks like a simple error in your Do While loop. You Check for the EOF instead of not the EOF, as such the loop will never execute since it starts at the BOF.

Something like this should work (my syntax may be slightly off as I haven't used VBA in a while)

Open "C:\file1.csv" For Input As #file_number
While Not EOF(file_number) And found <> False
    Line Input #file_number, raw_line
    pos = InStr(raw_line, fireName)
    If pos <> 0 Then
        strData() = Split(raw_line, ",")
        found = True
    End If
Wend
Close #file_number
If found = False Then
    MsgBox "Could not find it"
    Exit Sub
End If



回答2:


The correct way of typing If pos != 0 in VBA is

If pos <> 0

Now it works



来源:https://stackoverflow.com/questions/29660745/vba-script-always-returns-input-past-end-of-file-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!