Consulting

Results 1 to 4 of 4

Thread: Solved: Rename a text file from within Excel

  1. #1

    Solved: Rename a text file from within Excel

    Hello !

    I have a macro that imports data from a text file (*.txt).

    The name of this text file is in cell A1:

    Parts List 2008 - Vol 1.txt

    After the data is imported it's sliced, diced, moved around and whatnot.

    As the last action of the macro I would like it to rename the text file to a name I have in cell B1 that's put together by a formula:

    =LEFT(A1,LEN(A1)-4)&"(P).txt"

    Results in the new desired name:

    Parts List 2008 - Vol 1(P).txt

    Renaming the file lets me know that that particular data has been processed.

    Currently, after I'm done with the spreadsheet file I close Excel and go into Windows Explorer to rename the text file manually. If I could automate this is would be the icing on the cake.

    Thanks for any assistance you can offer.

    Al Stubna

  2. #2
    VBAX Mentor tstav's Avatar
    Joined
    Feb 2008
    Location
    Athens
    Posts
    350
    Location
    One way to do it is by copying it to a new file with the desired name and then deleting the original file.
    Another way would be by using FileSystemObject (same thing -copy/delete- though).

    Method 1 (Cells A1, B1 should contain Path+FileName)
    [vba]Sub Test_RenameFile()
    On Error GoTo ErrorHandler
    FileCopy Range("A1").value Range("B1").value
    Kill Range("A1").Value
    ErrorHandler:
    MsgBox "Error" 'be more elaborate here
    End Sub[/vba]

    Method 2 (again, use error handling)
    [vba]Sub Test_RenameFile()
    Dim objFile As Object
    Set objFile = CreateObject("Scripting.FileSystemObject")
    objFile.CopyFile Range("A1").Value, Range("B1").Value, True
    objFile.DeleteFile Range("A1").Value, True
    Set objFile = Nothing
    End Sub[/vba]
    He didn't know it was impossible, so he did it. (Jean Cocteau)

  3. #3
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    You don't even need for the file to be open, so you can process it, close it, then issue

    [vba]

    Name "C:\test\Trails.txt" As "C:\test\" & Range("B1").Value & ".txt"
    [/vba]
    Last edited by Bob Phillips; 03-17-2008 at 02:21 AM.
    ____________________________________________
    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

  4. #4
    Thanks guys!

    I used xld's method and it works great.

    Easier than I thought.

Posting Permissions

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