You can find the Excel tips you're looking at Pro-business Excel VBA Programming by entering the keyword in the textbox below and clicking the "Google Search" button.

Thursday, April 10, 2008

2 Ways Of Renaming A File In VBA

Sometimes in your business application programming using VBA, you'll find yourself in a situation wherein you need to rename a file. Macro Recording at this point will not be helpful as you cannot do the renaming in Excel interactivity. Here are two ways of doing it at a VBA level:

Sub DoRename()
Name "c:\test.xls" As "c:\test2.xls"
End Sub

Another way of doing it is by using the CreateObject function:

Sub DoRename()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile "c:\test.xls", "c:\test2.xls"
Set fso = Nothing
End Sub

Another function of this two routines is that it can be used to move a file from folder to another. Here are examples:

Sub DoMove()
Name "c:\folder1\test.xls" As "c:\folder2\test.xls"
End Sub

Moving a file using CreateObject function:

Sub DoRename()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile "c:\folder1\test.xls", "c:\folder2\test.xls"
Set fso = Nothing
End Sub




Click here to subscribe and receive Pro-business Excel VBA Programming tips.


If you like this post in Pro-business Excel VBA Programming, buy me a coffee.


1 comments:

Anonymous said...

Your blog is like an encyclopedia for those who want to know more about this. Thanks for the interesting information.