因此,我有一个名为“ 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,它对结果没有影响。
我将非常感谢您的帮助。
谢谢
答案 0 :(得分:0)
尝试使用变量并查看文件是否确实存在,您可以从ThisName打印名称,并查看该值是否确实是您想要的
Dim thisName as string
dim toThisName as string
thisName = fullPath & "indexpre.txt"
toThisName = fullPath & Cells(r, 3).Value & ".txt"
if vba.dir(thisName) = "" then
'file not found
stop
end if
Name thisName As toThisName
答案 1 :(得分:0)
尝试一下:
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