打开文件夹VBA中的最新文件

时间:2017-07-19 05:49:28

标签: excel vba excel-vba

嗨我想打开文件夹中的最新文件,当我运行以下代码获取运行时错误1004时,问题是LatestFile保存最新excel文件的上一个文件夹。注意 - 代码打开最新文件的前两个文件夹,然后收到错误。请让我知道如何解决这个问题。

    Sub Esskay()
    Dim foldname, FolderName, subfold1, subfold2, strFilename As String
    Dim FileName, myfile2, myFoldert As Workbooks
    Dim sht, ws As Worksheet
    Dim bottomMostRow As Long, rightMostColumn, Lastrow As Long
    Dim FileSys, objFile, myFolder, c As Object   
    Dim misfile As Workbook    
    Dim rngLocation, rngLocation2 As Range
        Dim rngNewCol As Range
        Dim lrow, lrw, lcol As Long
         Dim MyFiled As String
        Dim LatestFile, Mypath As String
        Dim LatestDate As Date
        Dim LMD As Date


                    foldname = "C:\Users\ashokkumar.d\Desktop\Test\"

                    Lastrow = Workbooks("as").Sheets(1).Range("A" & Rows.count).End(xlUp).Row

      For k = 2 To Lastrow
                    subfold1 = Workbooks("as").Sheets(1).Cells(k, 1).Value
                    subfold2 = Workbooks("as").Sheets(1).Cells(k, 2).Value

                    FolderName = (foldname + subfold1 + "\" + subfold2 + "\" + "MIS" + "\")

        'Make sure that the path ends in a backslash
        If Right(FolderName, 1) <> "\" Then FolderName = FolderName & "\"

        'Get the first Excel file from the folder
        MyFiled = Dir(FolderName & "*.xls")

        'If no files were found, exit the sub
        If Len(MyFiled) = 0 Then
            MsgBox "No files were found...", vbExclamation
            Exit Sub
        End If

        'Loop through each Excel file in the folder
        Do While Len(MyFiled) > 0

            'Assign the date/time of the current file to a variable
            LMD = FileDateTime(FolderName & MyFiled)

            'If the date/time of the current file is greater than the latest
            'recorded date, assign its filename and date/time to variables
            If LMD > LatestDate Then
                LatestFile = MyFiled
                LatestDate = LMD
            End If

            'Get the next Excel file from the folder
            MyFiled = Dir

        Loop

        'Open the latest file
       Set myfile2 = Workbooks.Open(FolderName & LatestFile)
next
end sub

0 个答案:

没有答案