File Renaming Using VBA

sanilmathews

Board Regular
Joined
Jun 28, 2011
Messages
96
I have the below code which renames the files saved in path listed in column A with the names listed in column B (with file extension). The code is working fine.
However, I would like to have a provision in the same code that, if any of the cells in column A and B are empty then the code should skip to next non-empty cell in columns A and Column B.
<!--[if !supportLineBreakNewLine]-->
Code:
Sub Rename()
'Tools->Reference->Microsoft Scripting Runtime


Dim fso As New FileSystemObject
Dim fl As File
Dim r As Long


Worksheets("Sheet1").Select
For r = 1 To 45
    Set fl = fso.GetFile(Cells(r + 1, "A")) 'Paths
    fl.Name = Cells(r + 1, "B") 'New File Name
On Error GoTo Errorhandler
    Next
Errorhandler: Exit Sub
End Sub
<!--[endif]-->
 

Some videos you may like

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.

lrobbo314

Well-known Member
Joined
Jul 14, 2008
Messages
3,033
Office Version
  1. 365
Platform
  1. Windows
This is how I would do it.

Code:
Sub RenameFiles()
Dim ws As Worksheet:    Set ws = Sheets("Sheet1")
Dim LR As Long:         LR = ws.Range("A" & Rows.Count).End(xlUp).Row()
Dim R As Range:         Set R = ws.Range("A1:B" & LR)
Dim AR() As Variant:    AR = R.Value


For i = LBound(AR) To UBound(AR)
    If Not IsEmpty(AR(i, 1)) Then
        Name AR(i, 1) As AR(i, 2)
    End If
Next i


End Sub
 

Watch MrExcel Video

Forum statistics

Threads
1,122,964
Messages
5,599,071
Members
414,281
Latest member
Engjamal2021

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top