比较VBA中修改的文件日期

时间:2016-03-10 21:25:00

标签: excel vba excel-vba datemodified

所以我在VBA中编写一个代码,用于打开文档中的所有文件,并复制和粘贴每个文档中的信息。代码设置为打开每个文档,但本身。我的困境是我希望代码打开在主文件被修改的最后一天之后修改过的文档。基本上我想比较两个日期,一个日期保持不变,另一个日期在每个循环后更改(每个循环的新文档)。我的代码如下,任何帮助或建议将不胜感激。谢谢!

Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim DateMaster As Date
Dim DateReflections As Date

Filepath = "Path of folder where all the documents are"
MyFile = Dir(Filepath)
DateReflections = FileDateTime(Filepath)
DateMaster = FileDateTime("Filepath of master document I'm comparing to")

Do While Len(MyFile) > 0
 If MyFile = "zmasterfile.xlsm" Then
Exit Sub
 If DateReflections < DateMaster Then
Exit Sub
End If

Workbooks.Open (Filepath & MyFile)
Range("B4:N4").Copy
ActiveWorkbook.Close

erow = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("Reflections").Range(Cells(erow, 2), Cells(erow, 14))

MyFile = Dir

Loop
End Sub

2 个答案:

答案 0 :(得分:1)

你不应该在你的if语句中退出sub。您可以考虑将IF语句更改为以下内容:

Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim DateMaster As Date
Dim DateReflections As Date

Filepath = "Path of folder where all the documents are"
MyFile = Dir(Filepath)
DateReflections = FileDateTime(Filepath)
DateMaster = FileDateTime("Filepath of master document I'm comparing to")

Do While Len(MyFile) > 0
    DateReflections = FileDateTime(Filepath)
    If MyFile <> "zmasterfile.xlsm" and DateReflections > DateMaster Then

        Workbooks.Open (Filepath & MyFile)
        Range("B4:N4").Copy
        ActiveWorkbook.Close

        erow = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
        ActiveSheet.Paste Destination:=Worksheets("Reflections").Range(Cells(erow, 2), Cells(erow, 14))

    End If

    MyFile = Dir

Loop
End Sub

答案 1 :(得分:1)

您只需要在循环中重置DateReflections,使用MyFile构建文件路径。见下文。

If MyFile = "zmasterfile.xlsm" Then
Exit Sub

DateReflections = FileDateTime(Filepath & "\" & MyFile)
If DateReflections < DateMaster Then
Exit Sub
End If

顺便说一句,如果您只是跳过该文件并继续处理,而不是完全退出该子版本,请将Exit Sub替换为Continue Do }