比较在VBA中修改的文件date

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

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 

你不应该退出你的if语句中的子。 您可能会考虑将您的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 

您只需要在您的循环中重置DateReflections ,使用MyFile构build文件path。 见下文。

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

另外,如果您想跳过文件并继续处理,而不是完全退出子文件,请使用“ Continue DoreplaceExit Sub

Interesting Posts