首页 > 解决方案 > 按名称重命名多个文件 Excel VBA

问题描述

我对 vba 很陌生,我需要一个 excel 宏,它根据文件名为其分配另一个名称,例如:

aaa12345.txt -----> hello.txt
bb678.txt -----> bye.txt

文件夹中只有两种名称,aaa*.txt 和 bb*.txt

Sub rena_me()
if ffile = Dir("C:\test\aaa*.txt") Then NewName = "yellow.txt"
Name "C:\test\" & ffile As "c:\test\" & NewName
End sub

这段代码是我所拥有的......工作正常,但我不知道如何为这两个文件实现它

标签: excelvba

解决方案


试试下面的宏...

Option Explicit

Sub rena_me()

    Dim myPath As String
    Dim myFile As String
    Dim newName As String

    myPath = "C:\test\"

    'check for an aaa file
    myFile = Dir(myPath & "aaa*.txt")
    If Len(myFile) > 0 Then
        Name myPath & myFile As myPath & "hello.txt"
    End If

    'check for a bb file
    myFile = Dir(myPath & "bb*.txt")
    If Len(myFile) > 0 Then
        Name myPath & myFile As myPath & "bye.txt"
    End If

End Sub

推荐阅读