2016-03-10 42 views
0

因此,我正在VBA中編寫一個代碼,用於打開文檔中的所有文件並複製和粘貼來自每個文檔的信息。代碼設置爲打開每個文檔,但本身。我的困境是,我希望代碼打開在主文件被修改的最後一天之後修改過的文檔。基本上我想比較兩個日期,一個日期保持不變,另一個日期在每個循環之後更改(每個循環都有一個新文檔)。我的代碼如下,任何幫助或建議將不勝感激。謝謝!在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 

回答

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 
+0

好的建議更換您的Exit Sub s到重構 –

1

你只需要重置你的循環中DateReflections,使用MyFile打造的文件路徑。見下文。

If MyFile = "zmasterfile.xlsm" Then 
Exit Sub 

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

順便說一句,如果你想只跳過文件並繼續進行處理,而不是完全退出子,與Continue Do

+0

感謝幫助!日期反射的作品,但繼續做不會和兩個文件日期不正確比較。對此有何想法?謝謝! –