Consulting

Results 1 to 3 of 3

Thread: When using open text file how to tell if the file existed, or a file was created?

  1. #1
    VBAX Regular
    Joined
    Jun 2017
    Posts
    23
    Location

    When using open text file how to tell if the file existed, or a file was created?

    I'm working on a quick script that will export some data from excel into a text file. I have it all working, but I would like to be able to tell if the file already existed, or if it had to be created. The reason for this is if the file I was created I would like to add a header to the text file, so each column is able to be read quickly. If the file already existed, then there will be a header and no need for the header to be applied.

    Dim fs, f
    Set fs = CreateObject("scripting.FileSystemObject")
    Set f = fs.opentextfile("C:\..." & part & ".txt", 8, True, TristateUseDefault))
    f.write ....
    f.writeline
    f.Close
    part is the part number which is taken from a cell, which is also the name of the text file.

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    If Len(Dir("C:\..." & part & ".txt")) > 0 Then
        'Proceed
    Else
        'Add headers
    End If
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    VBAX Regular
    Joined
    Jun 2017
    Posts
    23
    Location
    Yup figured it out right after posting. Original thought was trying to see if I could get a returned value from opentextfile, but just did what you posted.

Posting Permissions

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