0

所以我正在用 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
4

2 回答 2

1

您不应该在 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
于 2016-03-10T21:38:54.040 回答
1

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

If MyFile = "zmasterfile.xlsm" Then
Exit Sub

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

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

于 2016-03-10T21:39:46.283 回答