Excel VBA打开文件与最新版本

时间:2015-11-13 09:16:07

标签: excel-vba vba excel

刚刚开始学习VBA for excel并尝试自动化我的日常工作。 我有一个工作簿,其中一些内容是从其他文件复制而来的。在同一个文件目录中,我有几个我复制的数据文件。问题是文件有多个版本控制,例如:

  • companyA_20151101.xlx
  • companyA_20151105.xlx
  • companyA_20151106.xlx
  • companyB_20151105.xlx
  • companyC_20151109.xlx

我从A公司到C公司的文件,但由于日期有问题。是否有可能告诉VBA选择最新版本(即公司A采用06日期的那个)?

2 个答案:

答案 0 :(得分:1)

您可以创建UDF以返回具有正确文件名的字符串。我从命名约定中假设最近的文件实际上是创建的,因此将具有最新的Creation Date属性。

Function GetRecentFile(partialFileName As String) As String

Dim files As Variant
Dim checkDate As Date
Dim returnFile As String

With CreateObject("System.FileScriptingObject")

    files = Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & partialFileName & _
        "*.xl*"" /S /B /A:-D").StdOut.ReadAll, vbCrLf), ".")

    checkDate = .GetFile(CStr(files(0))).DateCreated

    For Each file In files
        If .GetFile(CStr(file)).DateCreated > checkDate Then
            checkDate = .GetFile(CStr(file)).DateCreated
            returnFile = CStr(file)
        End If
    Next

End With

GetRecentFile = returnFile

End Function

像这样使用:

Sub MM()

Dim myFile As String, wb As Excel.Workbook

myFile = GetRecentFile("C:\Users\MM\Work Files\CompanyA")

If Not myFile = vbNullString Then
    Set wb = Workbooks.Open(myFile)
End If

End Sub

答案 1 :(得分:0)

我对此略有不同,并且使用文件名上的日期后缀来确定哪个是最新的'文件:

Public Function MostRecentCompanyFile(ByRef strCompany As String, _
                                    ByRef strDirectory As String) As String

Dim strDir          As String
Dim datDateSuffix   As Date
Dim strLatest       As String
Dim datLatest       As Date

strDir = Dir(strDirectory & "\" & strCompany & "*")

Do Until Len(strDir) = 0
    datDateSuffix = StripDate(strDir)

    If Len(strLatest) = 0 Then
        'the first iteration
        strLatest = strDir
        datLatest = datDateSuffix
    ElseIf datDateSuffix > datLatest Then
        'this file has a later date suffix so this is now the latest
        strLatest = strDir
        datLatest = datDateSuffix
    End If
    'get the next file
    strDir = Dir
Loop

MostRecentCompanyFile = strLatest

End Function

Private Function StripDate(ByRef strFileName As String) As Date

Dim intPos  As Integer
Dim strDate As String
Dim datDate As Date

'assume the date suffix occurs after the underscore in the file name and is in the format yyyymmdd
intPos = InStr(1, strFileName, "_")

strDate = Mid$(strFileName, intPos + 1, 8)

datDate = DateSerial(Left$(strDate, 4), Mid$(strDate, 5, 2), Right$(strDate, 2))

StripDate = datDate

End Function

我们在这里:

  1. 循环显示给定strDirectory中的所有文件。
  2. 剥去日期后缀(使用StripDate方法)。
  3. 将此日期与给定strCompany的所有其他日期进行比较。