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

fixing error subscript out of range

0

hi

I  face   problem  with  this  code .  it  should  rename  the  files  based on  the  columns .

first  the  code  matches  names  are  existed  into headers  with  the  directory   and  rename  the  files    but  it  just  works  in subfolder contains  files  extensions  .PDF  and  show error   "subscript  out  of  range"  in this  line 

 OldName = MYPATH & FileExt & "\" & FileList(i - 1)

this  is  the  whole  code 

Sub rename5()


    Const MYPATH As String = "C:\Users\LP PC\Desktop\fl\"

    Dim LastCol As Integer, LastRow As Long
    Dim i As Integer, j As Integer
    Dim NewName As String, FileExt As String, OldName As String
    Dim FileName As String, FileList() As String, lCount As Long

    LastCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

    For j = 1 To LastCol
        LastRow = ActiveSheet.Cells(Rows.Count, j).End(xlUp).Row
        FileExt = Cells(1, j).Value

        lCount = 0
        FileName = Dir(MYPATH & FileExt & "\")
        While Len(FileName) > 1
            lCount = lCount + 1
            ReDim Preserve FileList(1 To lCount)
            FileList(lCount) = FileName
            FileName = Dir()
        Wend

        For i = 2 To LastRow

            NewName = MYPATH & FileExt & "\" & Cells(i, j).Value & "." & FileExt
            OldName = MYPATH & FileExt & "\" & FileList(i - 1)

            Name OldName As NewName

        Next i

    Next j

    MsgBox "Done!"

End Sub
Answer
Discuss

Answers

0
Selected Answer

Hello Kalil,

I think the error has to do with a missing reset of the array FileList(). I added that and changed the indexing of the array at the same time so that the index number in the array coincides with the row number in the ActiveSheet.

Sub RenameFiles5()
    ' 275

    Const MYPATH As String = "C:\Users\LP PC\Desktop\fl\"

    Dim Ws As Worksheet
    Dim LastCol As Long, LastRow As Long
    Dim R As Long, C As Long            ' rows and columns should be Long integers
    Dim NewName As String, FileExt As String, OldName As String
    Dim FileName As String, FileList() As String, i As Integer

    Set Ws = ActiveSheet        ' dangerous! replace with Worksheets("Tab name")
    LastCol = Ws.Cells(1, Ws.Columns.Count).End(xlToLeft).Column

    For C = 1 To LastCol
        FileExt = Ws.Cells(1, C).Value
        ReDim FileList(2 To 1000)
        i = 1
        FileName = Dir(MYPATH & FileExt & "\")
        While Len(FileName) > 1
            i = i + 1
            FileList(i) = FileName
            FileName = Dir()
        Wend

        If i > 1 Then
            ReDim Preserve FileList(2 To i)

            LastRow = Ws.Cells(Ws.Rows.Count, C).End(xlUp).Row
            For R = 2 To LastRow
                OldName = MYPATH & FileExt & "\" & FileList(R)
                NewName = MYPATH & FileExt & "\" & Ws.Cells(R, C).Value & "." & FileExt
                Name OldName As NewName
            Next R
        End If
    Next C

    MsgBox "Done!"
End Sub

Your original code oscillates between using the ActiveSheet by name and by default. Using it be name should be restricted to when it doesn't have a name. This only happens when a new sheet is created by code. Using it by default isn't good practice because you can never be sure which sheet the user activated unless you call the code with a button. But to use both by name and by default in one procedure intends to confuse the programmer, and that is never a good idea.

Another thing you might like to learn is that when you use Redim Preserve VBA will create a completely new array, transferring all values from the previous to the new, one by one. That is time consuming and should therefore be avoided doing in a loop. It's better to declare the array as too large initially and then redim it only once the required number of elements is known. I have implemented this method in your code. I allowed for 1000 files. You can increase that number without ill effect.

Discuss

Discussion

thanks
but  it  gives  the  same  error  in this  line 
OldName = MYPATH & FileExt & "\" & FileList(R)
Kalil (rep: 36) Jul 4, '21 at 4:03 am
My code is tested. The error results from your setup. So we ned to take a 2-prongued approach. One, the error is caused by the number of files in the directory and the number of names in the list not being the same. Two, there shouyldn't be a crash, but what do you want to happen instead?
Look at your column J where the extension is "TEXT". In your setup the column caption, the flder name and the file extension are all the same. There is no file extension "TEXT". It's "TXT". My code passes over the error without warning. That isn't good, either. Do you want the other error passed over in the same way?
I think your entire plan is not worth repairing. Bear in mind that the sequence in which the files are found in the folder may not be the same as the sequence in your list. So, why not discard the list? It appears to be useless but it's the cause of your present trouble. All you want is all the files in folder PDF to be named with "PPD-" and a number from 1000 up. JPG and PNG same, GIF "AS-GIF" and 123 > up.
Variatus (rep: 4889) Jul 4, '21 at 6:04 am
So, you only need the folder name and associate a prefix and a first number with that: PDF > PPD- > 1000, JPG > JPG- > 1000, GIF > AS-GIF > 123 etc. You can put this in a sheet with 3 columns.
Why 123 for GIF or 12 for DOCX? If the lower numbers are already taken (and, anyway!) you might find the next number by examining the file names in the folder and rename only those that are named by a different pattern. If so, you don't need a sheet. Put all the lists into constants in the code but work on your numbering to make it consistent. Start all numbers at 1 or at 1000. "XL12-EXCEL1" would be just as happy with a name like "XL12-1000", "TX1-TXT1" could be TX1-1000". I would avoid underscores in such a system. "MU_AS_12" would be better identified as "MP3-1011".
All of this to avoid having a sheet which needs maintenance. All you want is less work and clear names.
Variatus (rep: 4889) Jul 4, '21 at 6:04 am
sorry about  mistake  for extension TXT 
I  followed  your  notices  .  now  the  code  works .
many  thanks  for  your assistance . 
Kalil (rep: 36) Jul 4, '21 at 6:58 am
Add to Discussion


Answer the Question

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