Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

add text to pdf,excel files names

0

Hello,

in module 2 I would adapt code to deal with pdf files too.

currently I can add text to fle name after add amount with just EXCEL files . also I would do that with PDF files.

the code ask me enter amount based on files names are existed in column B after that ask me enter text to add to last part for file name  then will change file name in column B and directory in column C and add new file name in column A   and change within folders and subfolders. this happens for just EXCEL files but I would also do that with PDF files 

Sub test()
    Dim myDir$, s$, suf$, x, n&
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show Then myDir = .SelectedItems(1)
    End With
    If myDir = "" Then Exit Sub
    Do
        s = InputBox("Enter amount")
        If s = "" Then Exit Do
        suf = InputBox("Enter word")
        If suf = "" Then Exit Do
        x = SearchFiles(myDir & "\", "*" & s & ".xls*")
        If x <> "" Then
            n = n + IIf(n, 1, 2)
            Cells(n, 2) = CreateObject("Scripting.FileSystemObject").GetBaseName(x)
            Cells(n, 3) = x
            If Not IsFileOpen(x) Then
                Name x As Application.Replace(x, InStrRev(x, "."), 0, " " & suf)
                 Cells(n, 1) = Cells(n, 2) & " " & suf
            Else
                Cells(n, 4) = "Currently in USE " & Format(Now, "yyyy/mm/dd hh:mm:ss")
            End If
        Else
            MsgBox "Not found"
        End If
        If MsgBox("Do you want to continue?", vbQuestion + vbYesNo) <> vbYes Then Exit Do
    Loop
End Sub


Function SearchFiles$(myDir$, myFileName$)
    Dim fso As Object, myFolder As Object, myFile As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    For Each myFile In fso.GetFolder(myDir).Files
        If (Not myFile.Name Like "~$*") * (myFile.Name <> ThisWorkbook.Name) _
        * (myFile.Name Like myFileName) Then
            SearchFiles$ = myDir & myFile.Name
            Exit Function
        End If
    Next
    For Each myFolder In fso.GetFolder(myDir).SubFolders
        SearchFiles = SearchFiles(myFolder.Path & "\", myFileName)
    Next
End Function


Function IsFileOpen(ByVal fName$) As Boolean
    Dim ff&, errNum&
    On Error Resume Next
    ff = FreeFile
    Open fName For Input Lock Read As #ff
    Close ff
    errNum = Err
    On Error GoTo 0
    IsFileOpen = (errNum <> 0)
End Function

thanks

Answer
Discuss

Discussion

Hi again Kalil

Looks like your question relates to an earlier Anwer from me but I think it relies on your unique (and non-standard) way of naming your files. Therefore you need to help us out a bit- please edit your Question to:

    1) include the code on Module 2 (within CODE markers, using the button above)

    2) explain (by example) what you expect to happen when that code runs (and for pdfs too).

We should then be able to provide an Answer. Thanks in advance.
John_Ru (rep: 6722) Jul 4, '25 at 7:13 am
Hi John ,
I edited my post by add more detailes and code.
the only thing I need it the code should deal with pdf, excel files.
Kalil (rep: 44) Jul 4, '25 at 11:51 am
Thanks Kalil- that helps.

One further thing- do you ONLY have pdf files with the same name as an Excel file? E.g. can INVOICE 2,500.00.pdf exist without there being a file named INVOICE 2,500.00.xlsx?
John_Ru (rep: 6722) Jul 4, '25 at 4:42 pm
do you ONLY have pdf files with the same name as an Excel file?
surely there are same file name for pdf,excel files.
Kalil (rep: 44) Jul 5, '25 at 3:33 am
Thanks Kalil (though I'm not sure what you mean!). Am just crerating an Answer.
John_Ru (rep: 6722) Jul 5, '25 at 9:31 am
Add to Discussion

Answers

0

Kalil

In the attached, modified file I have made the changes( in bold below) to your main code in Module 2 so that:

  1. the input "Amount" (= end of filename in your case) is passed to the SearchFiles Function WITHOUT the extension (".xls*")
  2. that Function checks both  .xls and .pdf file types then returns a string which is split into an array called Arr (which is looped through using new count variable m).
Sub test()
    Dim myDir$, s$, suf$, x, n&
    Dim Arr As Variant, m As Long
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show Then myDir = .SelectedItems(1)
    End With
    If myDir = "" Then Exit Sub
    Do
        s = InputBox("Enter amount")
        If s = "" Then Exit Do
        ' make default any last suffix
        suf = InputBox("Enter word", , suf)
        If suf = "" Then Exit Do
        ' pass name WITHOUT extension (but check in Function)
        x = SearchFiles(myDir & "\", "*" & s) ' & ".xls*")

        If x <> "" Then
            ' split text into an array
            Arr = Split(x, ";")
            ' loop through array
            For m = 0 To UBound(Arr) - 1
                n = n + IIf(n, 1, 2)
                Cells(n, 2) = CreateObject("Scripting.FileSystemObject").GetBaseName(Arr(m))
                Cells(n, 3) = Arr(m)
                ' check/ rename file, using Trim to eliminate leading/trailing spaces
                If Not IsFileOpen(Trim(Arr(m))) Then
                    Name Trim(Arr(m)) As Trim(Application.Replace(Arr(m), InStrRev(Arr(m), "."), 0, " " & suf))
                    Cells(n, 1) = Cells(n, 2) & " " & suf
                Else
                    Cells(n, 4) = "Currently in USE " & Format(Now, "yyyy/mm/dd hh:mm:ss")
                End If
            Next m
            '  advise number of conversions or open files
            MsgBox ("Listed " & UBound(Arr) & " files.")
        Else
            MsgBox "Not found"
        End If
        If MsgBox("Do you want to continue in same folder?", vbQuestion + vbYesNo) <> vbYes Then Exit Do
    Loop
    ' resize columns
    Columns("A:D").AutoFit
End Sub

(I added a messgae after eacj successful check)

The Function SearchFiles now checks for both .xls* and .pdf extensions, changes in bold again, and returns a string like "file10.pdf; file10.xlsx" (if you chose Amount 10 say):

Function SearchFiles$(myDir$, myFileName$)
    Dim fso As Object, myFolder As Object, myFile As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    For Each myFile In fso.GetFolder(myDir).Files
        ' check all files for named extensions
        If (Not myFile.Name Like "~$*") * (myFile.Name <> ThisWorkbook.Name) _
        * ((myFile.Name Like myFileName & ".xls*") Or (myFile.Name Like myFileName & ".pdf")) Then
            ' add to string (with delimiter= ";")
            SearchFiles$ = SearchFiles$ & myDir & myFile.Name & "; "
            ' don't quit on first find but search all files
            'Exit Function
        End If
    Next
    For Each myFolder In fso.GetFolder(myDir).SubFolders
        SearchFiles = SearchFiles(myFolder.Path & "\", myFileName)
    Next
End Function

I made no changes to the Function IsFileOpen

Hope this fixes your problem- if so, please remember to mark this Answer as Selected. 

Discuss

Discussion

thanks,
unfortunaly show me file not found despite of I 'm sure right file name contains amount .
I tested with original code with the same file name and works but with your attachment show me file not found 
I'm not sure where is my bad!
Kalil (rep: 44) Jul 6, '25 at 1:11 pm
Hi again Kalil. As I said before, you use unusual file names (so perhaps my code doesn't work). I assumed yiur Amount was immediately before the. xlsx or. pdf extension (without any intervening space or character). . 

Which file name did you test (and did it show when you listed all files under the same head folder)? I could test using s file named the same (if that's allowed for Windows in English) 
John_Ru (rep: 6722) Jul 6, '25 at 5:30 pm
UPDATE: 

I renamed one of my files to be like one in your spreadsheet (invoice 5,000.00.xlsm). The revised code found that and renamed it as invoice 5,000.00 done.xlsm (using an wored seen in your spreadsheet).

Note that currently the code will NOT then find invoice 5,000.00 done.xlsm (since it assumes the amount is at the end of the base filename.

Is that what you need or can the amount be anywhere in the filename?
John_Ru (rep: 6722) Jul 7, '25 at 3:23 am
I tested many files INVOICE 1,000.00     ,  INVOICE 2,500.00    , INVOICE 5,000.00 
all of theses don't rename.
I suppose when write into inputbox 
first write 1,000.00
second write done  
third should rename INVOICE 1,000.00 done , right?
if it's so why doesn't work for  me?!
as to space before extension as you see when showing files in column  c there are no spaces! 
also I use copy name and paste to avoid any error when witing !
Kalil (rep: 44) Jul 7, '25 at 3:51 am
Hi again Kalil.

I'm puzzled! 

Yes, if you have a file named "INVOICE 1,000.00.pdf" say, then set Amount to "1,000.00" and Word to "done", it should rename the file to "INVOICE 1,000.00 done.pdf" (and likewise for any matching .xls* file).

You realise that if you also have a file "INVOICE 21,000.00.pdf"  that would be renamed too? Or do you enter the Amount as " 1,000.00" (with a leading space) to avoid that?

Let me know because I used the VBA function Trim in my code (which removes leading and trailing spaces from the full file name)- that may be a possible cause of your difficulty.

EXTRA:

Just to be sure- are you testing using my file (and clicking the "add text" button)?

I tried again- renamed one of my files to "APPVD INVOICE 77,725.00.xlsx", clicked that button, entered Amount "77,725.00" and Word "done". The file was then listed on the spreadsheet and I saw it was renamed to "APPVD INVOICE 77,725.00 done.xlsx", as expected. It also worked if I restored the file name and moved it to a subfolder.
John_Ru (rep: 6722) Jul 7, '25 at 7:07 am
whether use trim or not  or space before name or not doesn't work at ll !
surely I use your file.
I don't still know what's my problem if that works for you!
Kalil (rep: 44) Jul 7, '25 at 8:48 am
Kalil, presently Trim is needed in the code since converting the string to an array introduces a space (which can cause the code to not find a file which does exist).

I'm using it on a home PC (Windows 10) and it works well. Are you using a corporate PC but have write permissions in the folders you search? Did you try my file on another PC? 

Please note I'm going out now and won't be back for several hours (but will try to check your reply today)
John_Ru (rep: 6722) Jul 7, '25 at 8:59 am
what I notice when I try create new folder with files pddf,excel  then will work  very well ,but when try  delete  word is existed after amount  and try rename again then the code will not rename at all !
does code raname from just first time ?
also the code doesn't deal with the same file name for the same extension or different extension within folders and subfolders.
Kalil (rep: 44) Jul 7, '25 at 3:14 pm
Thanks Kalil. 

Regarding your question "Does the code rename  just the first time?", it works multiple times- I tested it by renaming the same .xls and a .pdf files several times. Note that if it added " done" to the filename, you need to delete " done" (including the space). Did you do that?
John_Ru (rep: 6722) Jul 7, '25 at 4:36 pm
you need to delete " done" (including the space). Did you do that? surely yes. what I notice when create new folder and put files inside it and try to  rename for specific files then will succeed  and if I rename new files and try to rename files have already renamed after delete done then the code will not work! so what I think code rename all of files name at once for one time in my case. this is really strange!
Kalil (rep: 44) Jul 8, '25 at 3:24 am
Kalil, You said "I think code rename all of files name at once" - you're right in that I removed the line in bold:
            Exit Function
        End If

so that the code did not stop after it found the first matching file.

An alternative approach would be to change the Function so that it does exit on first match but it receives the file type from the main code e.g..xls* first then. pdf.

I don't have time to do that today but might have time tomorrow.
John_Ru (rep: 6722) Jul 8, '25 at 5:24 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login