Excel 尝试重命名文件夹中的文件(基于文件名中的字符串)

Excel 尝试重命名文件夹中的文件(基于文件名中的字符串),excel,vba,Excel,Vba,您好,我正在尝试创建一个子文件夹,其中我在文件夹中找到一个文件,其名称包含一个特定短语,如“test_file”,并使用其他名称/扩展名对其重命名。我有以下代码似乎不起作用:(而且我不知道如何在文件名中搜索特定字符串并根据该字符串执行重命名) 任何帮助都将不胜感激 看看评论,你有几个错误 Sub ReName() Dim myFile As String Dim myPath As String Dim mVal As String mVal = "_12345

您好,我正在尝试创建一个子文件夹,其中我在文件夹中找到一个文件,其名称包含一个特定短语,如“test_file”,并使用其他名称/扩展名对其重命名。我有以下代码似乎不起作用:(而且我不知道如何在文件名中搜索特定字符串并根据该字符串执行重命名)


任何帮助都将不胜感激

看看评论,你有几个错误

Sub ReName()
    Dim myFile As String
    Dim myPath As String
    Dim mVal As String

    mVal = "_12345678_" 'test string'

    myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
    '' You weren't referencing MyPath here - guessing copy and paste error
    myFile = Dir(myPath & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
    myFile = myPath & myFile

    '' This was passing the variable as part of the string
    newname = "new_test_file" & mVal & ".xlsx" 'save it as .xlsx and with the new filename including myVal'

    Name myFile As myPath & newname 'rename

End Sub

如果我将路径设置为
“C:\Users\bf91955\Desktop\testfolder\”
我会得到“Path File Access Error”,如果我放弃了路径末尾的“\”,那么我会得到“Run time Error”53:“File not found”会回滚到原来的问题,因为将代码更新为@Toms code使它看起来没有问题。。。。i、 你的代码似乎不起作用,但确实起作用了,因为它是Toms代码。。。或者类似的。不管是哪种方式,我们都需要了解问题所在和答案,这样它才能帮助其他人。这一点是正确的,但我仍然得到“未找到文件”,因为它无法根据完整文件名的片段找到文件。就像文件的真实名称是'2222_test_test_file.xlsx',但我需要脚本来识别并根据片段'test_file'重命名文件,我不知道如何做。请检查您的路径是否正确。用户是否真的
bf91955
以及路径的大小写是否正确?确实正确,直接从文件资源管理器复制,有趣的是宏现在重命名了文件夹而不是文件LOL。此外,我刚刚注意到,如果您复制并粘贴了我的上面的代码,我将该文件作为“发票”(我在文件夹中的内容)保留以查找我已经为您将其更新回
test\u file
。我在myPath的末尾添加了一个“\”,现在它可以工作了:)它重命名了文件夹,而不是之前的文件哈哈。非常感谢你的帮助!因此,如果字符串在**之间,那么脚本只搜索该部分是否正确?
Sub ReName()
    Dim myFile As String
    Dim myPath As String
    Dim mVal As String

    mVal = "_12345678_" 'test string'

    myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
    '' You weren't referencing MyPath here - guessing copy and paste error
    myFile = Dir(myPath & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
    myFile = myPath & myFile

    '' This was passing the variable as part of the string
    newname = "new_test_file" & mVal & ".xlsx" 'save it as .xlsx and with the new filename including myVal'

    Name myFile As myPath & newname 'rename

End Sub