我正在尝试找出一行代码来打开文件。 路径是不变的,即
"H:\silly\goose\*filename.xlsm*"
但是,每次我尝试运行此宏时,此文件名都会更改。这是因为我将使用这个宏来自动生成每周运行的报告。每个报告都以标题中的日期保存,并且所有报告都保存在同一个文件夹中,这意味着我不能开始将它们命名为相同的名称。 示例:
H:\silly\goose\Report 06-03-15.xlsm
H:\silly\goose\Report 05-27-15.xlsm
唯一有用的信息是该报告将于每周三运行。因此,每个文件名会有 7 天的差异。不过,我不知道这里的 Date
方法是否可以做任何事情。
最佳答案
您需要做的是首先重新构建您的文件名。
Const fpath As String = "H:\silly\goose\" ' your fixed folder
Dim fname As String
' Below gives you the Wednesday of the week
fname = Format(Date - (Weekday(Date) - 1) + 3, "mm-dd-yy") ' returns 06-03-15 if run today
fname = "Report " & fname & ".xlsm" ' returns Report 06-03-15.xlsm
fname = fpath & fname ' returns H:\silly\goose\Report 06-03-15.xlsm
然后执行文件的打开:
Dim wb As Workbook
Set wb = Workbooks.Open(fname)
If wb Is Nothing Then MsgBox "File does not exist": Exit Sub
' Rest of your code goes here which works on wb Object
关于打开更改文件名的VBA代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630524/