0

I am trying to read data from another spreadsheet in the same folder as my currently opened workbook, whenever I run this code I get the error file already open. Is there something wrong with my syntax or anything that might stop this from happening?

Here is the code.

Sub ReadFile()
    Infile = ThisWorkbook.Path & "\smallDataset.csv"
    Open Infile For Input As #1
        Input #1, a, b
        Close #1
        Debug.Print (a & " " & b)
End Sub

Thanks.

Colours
  • 1
  • 1
  • 1
  • 3
  • What's the name of your *currently opened workbook*? (And nit-picking: A .csv file is not a spreadsheet; it's a text file of comma-separated values (AKA a *CSV file*).) – Ken White Dec 27 '17 at 00:51
  • Reboot your computer and try again. Also, add a line `Debug.Print ThisWorkbook.Path` to make sure it's returning the proper path. (For example, it will be _blank_ if your workbook hasn't been saved.) At first glance I think your syntax is a little off too, see [this detailed example](https://stackoverflow.com/a/12259729/8112776) of reading csv with VBA. – ashleedawg Dec 27 '17 at 01:29
  • If it's an error 55, it probably means that you already have a file open with a file handle of `#1`. (Not necessarily the **same** file, just any file.) Try entering `Close` (to close all open files) in the Immediate Window, and then run your code again – YowE3K Dec 27 '17 at 04:59

2 Answers2

1

Try the following code to make sure there is no file open with handle #1

Sub ReadFile()
    InFile = ThisWorkbook.Path & "\smallDataset.csv"
    Close #1
    Open InFile For Input As #1
        Input #1, a, b
        Close #1
        Debug.Print (a & " " & b)
End Sub

Or you use Freefile to get the next number

Sub ReadFile
FileNumber = FreeFile

InFile = ThisWorkbook.Path & "\smallDataset.csv"

    Open InFile For Input As FileNumber
        Input #FileNumber, a, b
        Close #FileNumber
        Debug.Print (a & " " & b)
End Sub
Storax
  • 11,158
  • 3
  • 16
  • 33
0

I am also experiencing the errors which you have, these are the probable causes of the said error.

1) The CSV is open along with the Excel file 2) Your code has memory leaks

To resolve number 1

  • Try running the VBA code when the CSV is not opened

To resolve number 2

  • Try to use close the CSVobject after you have written your data inside it.

I'm not sure about your full code, but please check if you have something like Excel.Close or Excel.Quit.

Mr.J
  • 430
  • 2
  • 10
  • 30