首页 > 解决方案 > 重命名多个子文件夹中的txt文件

问题描述

所以我有一个名为“Test”的文件夹,文件夹中有不同名称的子文件夹(在 A 列中),每个子文件夹中有一个名为“indexpre”的 txt 文件。

我需要将文件重命名为我在 excel C 列中的内容。

我尝试使用我在网上看到的其他代码,但我得到了同样的错误。

Sub ReNameFiles()

Dim myPath As String
Dim fullPath As String
myPath = "C:\Users\cooketd\Desktop\Test"

r = 1

For Each cell In Range("A1:A" & Range("A1").End(xlDown).Row)
    fullPath = myPath & "\" & cell & "\"

    Name fullPath & "indexpre.txt" As fullPath & Cells(r, 3).Value & ".txt"
   r = r + 1

Next cell

End Sub

当我运行代码时,我在这一行得到一个错误

Name fullPath & "indexpre.txt" As fullPath & Cells(r, 3).Value & ".txt"

说运行时错误'53':找不到文件。

我检查了源文件,文件路径正确,并且文件“indexpre.txt”存在。

我还从那行代码中删除了 .txt,它对结果没有任何影响。

我真的很感激任何帮助。

谢谢

标签: excelvba

解决方案


试试这个:

Sub tgr()

    Dim ws As Worksheet
    Dim aData As Variant
    Dim sInitialPath As String
    Dim sFullPath As String
    Dim sFileName As String
    Dim sFileToRename As String
    Dim i As Long

    Set ws = ActiveWorkbook.ActiveSheet
    aData = ws.Range("A1:C" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row).Value

    sInitialPath = Environ("UserProfile") & "\Desktop\Test"
    If Right(sInitialPath, 1) <> "\" Then sInitialPath = sInitialPath & "\"

    sFileToRename = "indexpre.txt"

    For i = LBound(aData, 1) To UBound(aData, 1)
        sFullPath = sInitialPath & aData(i, 1)
        If Right(sFullPath, 1) <> "\" Then sFullPath = sFullPath & "\"
        sFileName = Dir(sFullPath & sFileToRename)
        If Len(sFileName) > 0 Then Name sFullPath & sFileName As sFullPath & aData(i, 3) & ".txt"
    Next i

End Sub

推荐阅读