Consulting

Results 1 to 3 of 3

Thread: Open File for Output:: What if file does not exist?

  1. #1

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

    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:

    [VBA]
    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
    [/VBA]

    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

  2. #2
    I tried this, but "MkDir()" is giving me some issue:


    [VBA]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

    [/VBA]

    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?
    Last edited by Saladsamurai; 11-20-2009 at 07:35 AM.

  3. #3
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    [vba]

    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
    [/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •