使用单元格值在文件夹中查找文件,然后重命名为另一个单元格值
我在文件夹中有pdf文件(例如,c:\ myfiles”)。
在excel上,我有一个数字列表,该列中的数字列表与该文件夹中的文件名部分相关联(D列D上的单元格上的数字可以在文件名)。
在E列上,我有新的文件名,我想将其提供给具有列上数字的文件。
我需要:
- 读取D列中的值,并在指定的 在文件名的任何部分中具有该值的文件夹。例如,
如果D1具有“ 1234567”的数字,我想与 名称(xxxx1234567xxxxxxxx),“ x”是任何其他号码或字母。 - 如果找到了匹配文件,请将其重命名为E列中的值 同时还要保持文件扩展名(.pdf)。
- 仔细阅读整列直到列表结束,然后停止。
- 如果在D列中没有特定值的匹配文件,请跳过然后转到下一个。
此代码没有错误,但不会更改任何名称。
Sub FindReplace()
Dim objFolder As Object
Dim objFile As Object
Dim i As Long
Set objFolder = CreateObject("Scripting.FileSystemObject").GetFolder("C:\MyFiles")
i = 1
For Each objFile In objFolder.Files
If objFile.Name Like "*" & Cells(i, "D").Value & "*" Then
objFile.Name = Cells(i, "E").Value & ".PDF"
End If
i = i + 1: If i > Cells(Rows.Count, "D").End(xlUp).Row Then Exit For
Next objFile
End Sub
我还希望宏来使用户选择其选择的文件夹,而不是每次都必须使用相同的文件夹,但这是可选的。现在需要的是文件重命名。
I have PDF files in a folder (say, C:\MyFiles").
On Excel I have a list of numbers in column D which correlate partially to the filenames in that folder (the numbers on the cells on column D can be anywhere in the filenames).
On column E, I have new filenames I want to give to the files having the numbers on column D.
I need to:
- Read the value in column D, and look for a file in the specified
folder that has that value in any part of the filename. For example,
if D1 has the number "1234567", I want to find the file with the
name (xxxx1234567xxxxxxxxx), "x" being any other number or letter. - If a matching file is found, rename it to the value in column E,
while also keeping the file extension (.pdf). - Read through the whole column until the end of list, then stop.
- If no matching file for a specific value in column D, skip and go to the next one.
This code shows no error, but it doesn't change any names.
Sub FindReplace()
Dim objFolder As Object
Dim objFile As Object
Dim i As Long
Set objFolder = CreateObject("Scripting.FileSystemObject").GetFolder("C:\MyFiles")
i = 1
For Each objFile In objFolder.Files
If objFile.Name Like "*" & Cells(i, "D").Value & "*" Then
objFile.Name = Cells(i, "E").Value & ".PDF"
End If
i = i + 1: If i > Cells(Rows.Count, "D").End(xlUp).Row Then Exit For
Next objFile
End Sub
I would also like the macro to make the user select a folder of their choosing, rather than having to use the same folder every time, but that is optional. What is needed right now is the file renaming.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为使用
dir()
查找部分匹配有点容易:It's a little easier I think to use
Dir()
to find partial matches: