VBA代码打开更改的文件名称

我试图找出一行代码来打开一个文件。 path是不变的,也就是说

"H:\silly\goose\*filename.xlsm*" 

但是,每次我尝试运行这个macros时,这个文件名都会改变。 这是因为我将使用这个macros来自动化每周运行的报告。 每个报告都与标题中的date一起保存,所有报告都保存在同一个文件夹中,这意味着我不能只是将它们命名为相同。 例子:

H:\傻\鹅\报告06-03-15.xlsm
H:\傻\鹅\报告05-27-15.xlsm

唯一有帮助的信息是,这个报告将在每个星期三运行。 因此,每个文件名将有7天的差异。 不过,我不知道在这里有没有什么可以用Date方法做的。

你需要做的是重新构build你的文件名。

 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 

这个引用有这个function:

 Function GetFileList(FileSpec As String) As Variant ' Returns an array of filenames that match FileSpec ' If no matching files are found, it returns False Dim FileArray() As Variant Dim FileCount As Integer Dim FileName As String On Error GoTo NoFilesFound FileCount = 0 FileName = Dir(FileSpec) If FileName = "" Then GoTo NoFilesFound ' Loop until no more matching files are found Do While FileName <> "" FileCount = FileCount + 1 ReDim Preserve FileArray(1 To FileCount) FileArray(FileCount) = FileName FileName = Dir() Loop GetFileList = FileArray Exit Function ' Error handler NoFilesFound: GetFileList = False End Function 

现在你可以做:

 p = "H:\silly\goose\*.xlsm" x = GetFileList(p) 

并得到你想要的文件