vba Excel宏用部分文件名打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41846874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:57:04  来源:igfitidea点击:

Excel macro to open file with partial filename

excelvbaexcel-vba

提问by Baber62

I have tried looking on various forums and cannot seem to find a solution that fits my needs.

我尝试在各种论坛上查找,但似乎无法找到适合我需求的解决方案。

I have a file "BABERs FORMULAS - 24 Jan 2017 - Rev 079 11-27.xlsm". I use a macro to save the changes to the file which adds the date, revision number and timestamp to the filename. The file is located at the following path "D:\FORMULAS".

我有一个文件“BABERs FORMULAS - 24 Jan 2017 - Rev 079 11-27.xlsm”。我使用宏来保存对文件的更改,该文件将日期、修订号和时间戳添加到文件名中。该文件位于以下路径“D:\FORMULAS”。

The macro I have is as below but this then gives me a Run-time error '1004' and says to check that the spelling of the file name and verify the location is correct.

我拥有的宏如下,但这会给我一个运行时错误“1004”,并说要检查文件名的拼写并验证位置是否正确。

Dim fname as Variant
fname = Dir("D:\FORMULAS\BABERs FORMULAS*")

If fname <> "" then
    Workbooks.open (fname)
End If

Any ideas where I could be going wrong? Any assistance would be appreciated.

我可能会出错的任何想法?任何援助将不胜感激。

回答by Shai Rado

Try something like the code below:

尝试类似下面的代码:

Dim fname As Variant
Dim myPath As String

myPath = "D:\FORMULAS\"
fname = Dir(myPath & "BABERs FORMULAS*")

If fname <> "" Then
    Workbooks.Open (myPath & fname)
End If