PDA

View Full Version : Open File for Output:: What if file does not exist?



Saladsamurai
11-20-2009, 06:46 AM
I have a loop, for each iteration it creates a new text file.

I want it to write the file to a particular folder; if that folder does not exist, I want Excel to create it.

For example:


Sub Test3()

Dim i As Integer

For i = 1 to 3
Open "Z:\Casey B\Main Folder\NewFile" & i & ".txt" For Output As #3
Print #3, i
Close #3
Next

End Sub


The results oft is should be as follows: If the folder "Main Folder" does not exist (which it does not on the FIRST iteration), then create it.

When the loop completes, there should be one folder called "Main Folder" and it should contain 3 text files...NewFile1, NewFile2, NewFile3.

As it stands, I get a "Path Not Found" error (duh...).

How can I remedy this?

Thanks so much,
Casey B

Saladsamurai
11-20-2009, 07:23 AM
I tried this, but "MkDir()" is giving me some issue:


Sub Test3()

Dim i As Integer


For i = 1 To 3
MkDir ("Z:\Casey B\Main Folder)
Open "Z:\Casey B\Main Folder\NewFile" & i & ".txt" For Output As #3
Print #3, i
Close #3
Next

End Sub



It creates the folder "Main Folder" just fine.....but then it cannot seem to access it to open:

"Z:\Casey B\Main Folder\NewFile" & i & ".txt" For Output As #3

I get a runtime 75 error ... something about the Path...

Any thoughts?

Bob Phillips
11-20-2009, 07:39 AM
Sub Test3()

Dim i As Integer

On Error Resume Next
MkDir "Z:\Casey B"
MkDir "Z:\Casey B\Main Folder"
On Error GoTo 0

For i = 1 To 3
Open "Z:\Casey B\Main Folder\NewFile" & i & ".txt" For Output As #3
Print #3, i
Close #3
Next

End Sub