Open FileName For Input As #FileNum2 - - - File Already Open!

  • Thread starter nouveauricheinvestments
  • Start date
N

nouveauricheinvestments

Hi,

I wrote the following script to parse all of my text files in a
specific folder into one. It is not working though. When it gets to
this line: Open FileName For Input As #FileNum2 , It tells me the
file is already open. I restarted my computer and I don't see it
open. I have at the end of the script Close #FileNum2 which I used
when the code was interrupted to try and close the file. How should I
be doing this or why would it be giving me this error?

Thanks for your help.

Sub parsedatafiles()

Dim ObjFSO As Object
Dim ObjFolder As Object
Dim ColFiles As Object
Dim objFile As Object
Dim FolderPath As String
Dim FileNum As Integer
Dim FileNum2 As Integer
Dim FileName As String

FileNum = FreeFile
FileNum2 = FreeFile
FolderPath = "Q:\DropBox\csv Files\Reject Enter\"

Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFolder = ObjFSO.getfolder(FolderPath)
Set ColFiles = ObjFolder.Files

Open FolderPath & "MyFileToAppend.Txt" For Append As #FileNum


For Each objFile In ColFiles
FileName = FolderPath & objFile.Name
Open FileName For Input As #FileNum2
Do Until EOF(FileNum2)
Line Input #FileNum2, Data
Write #FileNum, Data
Loop
Close #FileNum2
Next

Close #FileNum
Close #FileNum2

End Sub
 
M

Mike H

Hi,

When you create the 2 filenums with freefile they are the same. Dont create
the second filenum until after you have used the first, See slight change to
code below.

Dim FolderPath As String
Dim FileNum As Integer
Dim FileNum2 As Integer
Dim FileName As String

FileNum = FreeFile
FolderPath = "Q:\DropBox\csv Files\Reject Enter\"

Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFolder = ObjFSO.getfolder(FolderPath)
Set ColFiles = ObjFolder.Files
Open FolderPath & "MyFileToAppend.Txt" For Append As #FileNum
For Each objFile In ColFiles
FileNum2 = FreeFile
FileName = FolderPath & objFile.Name
Open FileName For Input As #FileNum2
Do Until EOF(FileNum2)
Line Input #FileNum2, Data
Write #FileNum, Data
Loop
Close #FileNum2
Next

Close #FileNum
Close #FileNum2

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top