2017-01-03 54 views
-2

我想重命名文件夹中的文件。假设我在列A中有文件名,必须使用列B中的新值进行更改。请提出建议。另外,重命名时扩展名不应该改变。使用宏重命名文件夹中的文件

我曾尝试的代码如下:

Sub rename 
    Dim Source As Range 
    Dim OldFile As String 
    Dim NewFile As String 
    Set Source = Cells(1, 1).CurrentRegion 
    For Row = 1 To Source.Rows.Count 
     OldFile = ActiveSheet.Cells(Row, 1) 
     NewFile = ActiveSheet.Cells(Row, 2) 
     ' rename files 
     Name OldFile As Newfile 
    Next 
end sub 
+0

而你在SO或互联网上找不到任何东西来帮助你? – nightcrawler23

+0

@ nightcrawler23如果您发现然后粘贴代码。 – mad2

+0

使用谷歌搜索'excel vba重命名文件夹中的文件'可以得到141,000个结果 - 这些工作都没有? – YowE3K

回答

0

此修改您的代码将从NewFile去掉所有扩展(设置延伸比长5个字符不再):

Sub Rename() 
    Dim Source As Range 
    Dim OldFile As String 
    Dim NewFile As String 
    Dim Row As Long 
    Set Source = Cells(1, 1).CurrentRegion 
    For Row = 1 To Source.Rows.Count 
     OldFile = ActiveSheet.Cells(Row, 1) 
     NewFile = ActiveSheet.Cells(Row, 2) 
     'see if NewFile contains an extension 
     If InStr(Right(NewFile, 6), ".") > 0 Then 
      'if so, strip it off 
      NewFile = Left(NewFile, InStrRev(NewFile, ".") - 1) 
     End If 
     'append extension 
     NewFile = NewFile & Mid(OldFile, InStrRev(OldFile, ".")) 
     ' rename files 
     Name OldFile As NewFile 
    Next 
End Sub 
+0

它不起作用。当我将ade.jpg重命名为a1.jpg时,它将重命名为a1de.jpg – mad2

+0

@matangraj - 对不起,'Right'应该是'Mid',但我本来期望创建'a1e.jpg',而不是'a1de.jpg' – YowE3K

+0

那么哪一行需要更改? – mad2