如何编写VBA代码来重命名根文件夹下的所有文件夹? [英] How do I write a VBA code to rename all folders under a root folder?
问题描述
Sub rename_folder()
Dim old_name,new_name As String
For i = 2 To Sheets(1).Range(a1)。End(xlDown).Row
new_name = Left(Sheets(1).Cells ,1).Value,Len(Sheets(1).Cells(i,1).Value) - Len(Sheets(1).Cells(i,2).Value))
new_name = new_name& (1).Cells(i,3).Value
old_name = Sheets(1).Cells(i,1).Value
Name old_name As new_name
Next i
End Sub
如何获取它,以便此代码重命名父文件夹中的所有文件夹?任何帮助将不胜感激!谢谢。
有两种方法可以解决这个问题。第一个(也是较慢的一个)是使用旧名称打开每个文件,保存为新名称,然后移动到下一个。
我会推荐脚本风格的方法,使用文件系统对象,您可以在循环中移动文件(重命名它们)。
假定新旧文件名与父文件夹有相对路径:
Dim fso As New FileSystemObject,ParentFolder as string
ParentFolder =C:\Users\Me\ThisProject\
For i = 2 To (1).Range(a1)。End(xlDown).Row
new_name = Left(Sheets(1).Cells(i,1).Value,Len(Sheets(1).Cells ,1).Value) - Len(Sheets(1).Cells(i,2).Value))
new_name = new_name& (1).Cells(i,3).Value
old_name = Sheets(1).Cells(i,1).Value
'这将移动(重命名)旧文件到新的
fso.MoveFile(ParentFolder& old_name),(ParentFolder& new_name)
下一个i
I'm very new to VBA and have been messing around with a few codes for work. Essentially, I have a folder that contains 1000+ folders with different names--and I need to rename each folder. I have an excel sheet set up with the Original File Path, Old Folder name, and Desired Folder Name. I have found that this code works for the parent folder, but not the folders within it:
Sub rename_folder()
Dim old_name, new_name As String
For i = 2 To Sheets(1).Range("a1").End(xlDown).Row
new_name = Left(Sheets(1).Cells(i, 1).Value, Len(Sheets(1).Cells(i, 1).Value) - Len(Sheets(1).Cells(i, 2).Value))
new_name = new_name & Sheets(1).Cells(i, 3).Value
old_name = Sheets(1).Cells(i, 1).Value
Name old_name As new_name
Next i
End Sub
How do I get it so that this code renames all the folders within the parent folder? Any help would be much appreciated! Thanks.
There are 2 ways to go about this. The first (and much slower one) is to open each file with the old name, save as with the new name, and then move to the next.
I would reccomend the scripting style approach, using a file system object you can move files (rename them) within a loop.
Presuming the old and new file names have a relative path with them from some parent folder:
Dim fso As New FileSystemObject, ParentFolder as string
ParentFolder = "C:\Users\Me\ThisProject\"
For i = 2 To Sheets(1).Range("a1").End(xlDown).Row
new_name = Left(Sheets(1).Cells(i, 1).Value, Len(Sheets(1).Cells(i, 1).Value) - Len(Sheets(1).Cells(i, 2).Value))
new_name = new_name & Sheets(1).Cells(i, 3).Value
old_name = Sheets(1).Cells(i, 1).Value
'This will move (rename) the old file to the new one
fso.MoveFile (ParentFolder & old_name), (ParentFolder & new_name)
Next i
这篇关于如何编写VBA代码来重命名根文件夹下的所有文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!