旧文件名在A列中,新文件名在B列中,如何使用VBA将旧文件名替换为目录中的新文件名?

时间:2017-12-26 19:38:45

标签: vba excel-vba excel

我有一个excel文件,有两列,A列和A列。 B栏。

A列是"已选择的路径和文件名",其中包含网络目录中每个文件名的路径:

\\xxx\yyyy\gggg\ooo.pdf
\\xxx\yyyy\gggg\ogh.pdf
\\xxx\yyyy\gggg\pjo.pdf

B列有"新文件名",它们应该替换旧文件名(ooo.pdf,ogh.pdf,pjo.pdf):

fff.pdf
fgh.pdf
hjk.pdf

我有一个代码,应该用新文件名重命名旧文件名,但不知怎的,它不能有效地工作。请告诉我以下代码有什么问题:

Sub RenameFiles()
Dim xDir As String
Dim xFile As String
Dim xRow As Long
With Application.FileDialog(msoFileDialogFolderPicker)
    .AllowMultiSelect = False
If .Show = -1 Then
    xDir = .SelectedItems(1)
    xFile = Dir(xDir & Application.PathSeparator & "*")
    Do Until xFile = ""
        xRow = 0
        On Error Resume Next
        xRow = Application.Match(xFile, Range("A:A"), 0)
        If xRow > 0 Then
            Name xDir & Application.PathSeparator & xFile As _
            xDir & Application.PathSeparator & Cells(xRow, "B").Value
        End If
        xFile = Dir
    Loop
End If
End With
End Sub

请告诉我可以用目录中的新文件名替换旧文件名的VBA代码。

1 个答案:

答案 0 :(得分:1)

您可以使用FileSystemObject:

Sub Iterator()

    'Tools -> References -> Microsoft Scripting Runtime
    Dim fso As New FileSystemObject
    Dim fl As File
    Dim r As Long

    For r = 1 To 3
        Set fl = fso.GetFile(Cells(r, "A")) 'Path is taken from column "A"
        fl.Name = Cells(r, "B") 'Rename with name taken from column B
    Next

End Sub