2015-06-03 46 views
2

我想弄清楚一行代码来打开文件。 路径是不变的,那就是VBA代码打开更改文件名

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

然而,这个文件的名字将每一次我尝试运行此宏观变化。这是因为我将使用这个宏来自动执行每周运行的报告。每个报告都与标题中的日期一起保存,所有报告都保存在同一个文件夹中,这意味着我不能只是将它们命名为完全相同。 例子:

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

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

+1

你能证明你用它来拯救* *文件名中的代码?逻辑应该几乎相同。 –

+3

否则,我们需要更多信息。应用程序应该如何知道要打开哪个文件?它是否总是打开*最近的*文件(即,<7天前生成的文件? –

+0

)使用您给出的2个示例,我们知道“06-03-15”>“05-27-15”。通过文件名进行这种比较,如果为真,那么让新文件比较文件名打开,最高的数字自然会冒泡到表面上。 –

回答

0

This reference具有这样的功能:

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) 

并获得文件你想

2

你需要做的是什么重新构造你的文件名第一。

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 
+0

你能解释一下这行代表什么意思?:Format(Date - Weekday(Date)+ 3 ,“mm-dd-yy”)我删除了-1,因为这个宏应该总是在星期三运行。但是,我仍然不明白星期几(日期)+3 – Tawm

+0

@Tawm这个简单的获取*星期三*,这样你就可以创建一个文件,所以本周它会返回* 6/3/2015 *,但下周运行它将返回* 2013年6月10日*。现在,如果这不是你所需要的,相应地修改你的问题并解释一些你需要的东西。 – L42