我很感激你在這方面的幫助。
我需要執行以下操作:我在一個檔案夾中有一些檔案(例如,C:\MyFiles"),其中包含一堆 PDF。在 Excel 中,我在 D 列中有一個數字串列,這些數字與其中的檔案名部分相關檔案夾(即 D 列上的單元格上的數字可以在檔案名中的任何位置)。在 E 列上,我有新的檔案名,我想給在 D 列上具有數字的檔案提供新的檔案名。
基本上,我需要一個可以:
- 讀取 D 列中的值,并在指定檔案夾中查找檔案名的任何部分具有該值的檔案。例如,如果 D1 有數字“1234567”,我希望它找到名稱為 (xxxx1234567xxxxxxxxx) 的檔案,“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
理想情況下,我還希望宏讓用戶選擇他們選擇的檔案夾,而不是每次都使用同一個檔案夾,但這是可選的。現在需要的是檔案重命名。
謝謝大家!
uj5u.com熱心網友回復:
我認為使用它Dir()來查找部分匹配會更容易一些:
Sub FindReplace()
Dim fPath As String, f, c As Range, ws As Worksheet
Dim i As Long
fPath = GetFolderPath("Select a folder for file renaming")
If Len(fPath) = 0 Then Exit Sub 'no folder selected
Set ws = ActiveSheet 'or some specific sheet
For Each c In ws.Range("D2:D" & ws.Cells(Rows.Count, "D").End(xlUp).row).Cells
If Len(c.Value) > 0 Then
f = Dir(fPath & "*" & c.Value & "*.pdf", vbNormal)
If Len(f) > 0 Then 'found a match?
Name fPath & f As fPath & c.Offset(0, 1).Value & ".pdf"
End If
End If
Next
End Sub
'get a folder from the user - returns empty string if no selection
Function GetFolderPath(msg As String) As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = msg
If .Show = -1 Then GetFolderPath = .SelectedItems.Item(1) & "\"
End With
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/484813.html
