用于打开更改文件名的VBA代码

时间:2015-06-03 20:55:12

标签: excel vba excel-vba

我试图找出一行代码来打开文件。 路径是常量,即

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

但是,每次尝试运行此宏时,此文件名都会更改。这是因为我将使用此宏来自动化我每周运行的报告。每个报告都与标题中的日期一起保存,所有报告都保存在同一个文件夹中,这意味着我无法开始将它们全部命名。 例子:

  

H:\ silly \ goose \ Report 06-03-15.xlsm
  H:\ silly \ goose \ Report 05-27-15.xlsm

唯一有用的信息是这份报告每周三开始运行。因此,每个文件名将有7天的差异。我不知道在这里我是否可以使用Date方法做任何事情。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

获取您想要的文件