Results 1 to 18 of 18

Thread: LISTING FILES IN FOLDER - INCORRECT ORDER

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #4
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,970
    Try the following (you don't need the FileSearch Class):
    Sub blah()
    Set fso = CreateObject("Scripting.FileSystemObject")
    myPath = ThisWorkbook.Path & Application.PathSeparator
    For Each R In Range("A1", Range("A" & Rows.Count).End(xlUp))
      Z = R.Value    '"06.Elephants"
      dot = InStr(Z, ".")    '3
      q = Left(Z, dot - 1)    '"06"
      OldName = "File" & q & ".pdf"    '"File06.pdf"
      NewName = Z & ".pdf"    '"06.Elephants.pdf"
      If fso.fileexists(myPath & OldName) Then Name fso.getfile(myPath & OldName) As myPath & NewName
    Next R
    End Sub
    This goes through the names in column A of the active sheet
    • Takes everything to the left of the first dot in those names (including leading zeroes) and
    • uses it to construct a filename to look for in the same folder as the workbook is in of the ilk: File06.pdf then
    • if it finds one renames it to what's in the cell in column A with .pdf tacked on..


    Bear in mind you said "files are just called File1.pdf, File2.pdf etc." whereas your picture suggests files are called File01.pdf, File02.pdf etc.

    ps.the above can be shortened to:
    Sub blah2()
    Set fso = CreateObject("Scripting.FileSystemObject")
    myPath = ThisWorkbook.Path & Application.PathSeparator
    For Each R In Range("A1", Range("A" & Rows.Count).End(xlUp))
      OldName = myPath & "File" & Left(R.Value, InStr(R.Value, ".") - 1) & ".pdf"
      If fso.fileexists(OldName) Then Name fso.getfile(OldName) As myPath & R.Value & ".pdf"
    Next R
    End Sub
    Last edited by p45cal; 02-18-2021 at 01:31 PM.
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from you.

Posting Permissions

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