使用VBA重命名文件 [英] Renaming files with VBA

查看:650
本文介绍了使用VBA重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在vba中重新命名文件。



我只知道文件名称的某一部分,例如,它以愉快开始。我想要将这个文件重命名为我想要的。只会有一个名为happy *的文件。我有下面的代码,但它给我一个文件未找到错误在名称ffile作为新名称

  Sub ReNaming ()

Dim ffile As String

ffile = Dir(h:\folder1\happy *)
NewName =yellow.xlsx
名称ffile为NewName


End Sub

我知道这可能不是正确的方式,但通配符的问题部分是导致所有的问题!



任何帮助将是伟大的。 / p>

谢谢

解决方案

问题是 Dir()返回文件名而不是完整路径。您可以在目录之后放入 Debug.Print ffile ,看看它返回的内容。如果该文件不存在于您正在运行VBA脚本的目录中,那么您将收到该错误。您可以执行以下操作:

  Sub ReNaming()

Dim ffile As String
Dim pathname As String

pathname =h:\folder1\
ffile = Dir(pathname&happy *)
ffile = pathname& ffile
NewName =yellow.xlsx
名称ffile As pathname& NewName或只是NewName,如果您想要*更改文件夹
End Sub


I'm having issue renaming files in vba.

I only know a certain part of the files name, for instance that it starts with happy. I want to be able to rename this file to whatever I want. There will only be one file called happy*. I've got the below code but it's giving me a "File not found" error on the Name ffile As NewName

Sub ReNaming()

Dim ffile As String

ffile = Dir("h:\folder1\happy*")
NewName = "yellow.xlsx"
Name ffile As NewName


End Sub

I'm aware this is probably not the correct way to be doing it but the wildcard part of the problem is causing all the issues!

Any help would be great.

Thanks

解决方案

The problem is that Dir() returns the file name but not the full path. You can put Debug.Print ffile after the Dir to see what it returns. If that file doesn't exist in the directory that you are running your VBA script in then you will get that error. You could do something like:

Sub ReNaming()

    Dim ffile As String
    Dim pathname As String

    pathname = "h:\folder1\"
    ffile = Dir(pathname & "happy*")
    ffile = pathname & ffile
    NewName = "yellow.xlsx"
    Name ffile As pathname & "NewName" 'or just "NewName" if you *want* to change the folder
End Sub

这篇关于使用VBA重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆