VBA:如何判断do循环中的if/else语句是否继续
因此,我编写了一个代码,通过文件夹打开文档,复制信息,然后粘贴到位于其他地方的主文件中。我遇到的问题是,我想添加if,else语句,以便将上次修改主文件的日期与其他文件夹中的文档进行比较。当它不符合if语句时,我希望循环跳过该文档并继续比较下一个文档。不确定如何进行此操作,代码如下所示VBA:如何判断do循环中的if/else语句是否继续,vba,excel,if-statement,do-loops,Vba,Excel,If Statement,Do Loops,因此,我编写了一个代码,通过文件夹打开文档,复制信息,然后粘贴到位于其他地方的主文件中。我遇到的问题是,我想添加if,else语句,以便将上次修改主文件的日期与其他文件夹中的文档进行比较。当它不符合if语句时,我希望循环跳过该文档并继续比较下一个文档。不确定如何进行此操作,代码如下所示 Sub Datecheck() Dim MyFile As String Dim erow Dim Filepath As String Dim otherfiledate As
Sub Datecheck()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim otherfiledate As Date
Dim zmasterdate As Date
Filepath = "folder of where all files are located"
MyFile = Dir(Filepath)
zmasterdate = FileDateTime("location of zmasterdate")
Do While Len(MyFile) > 0
otherfiledate = FileDateTime(Filepath & "\" & MyFile)
If otherfiledate > zmasterdate 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))
MyFile = Dir
Else
End Sub
End If
Loop
End Sub
您已经进行了检查,因此不需要else子句。只需将MyFile=Dir移动到循环的末尾
Sub Datecheck()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim otherfiledate As Date
Dim zmasterdate As Date
Filepath = "folder of where all files are located"
MyFile = Dir(Filepath)
zmasterdate = FileDateTime("location of zmasterdate")
Do While Len(MyFile) > 0
otherfiledate = FileDateTime(Filepath & "\" & MyFile)
If otherfiledate > zmasterdate 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
一个旁注,你不能在代码中间结束一个子,你需要<代码>退出子< /代码>。code>End Sub表示子例程的结束一些可能有用的注意事项:1)因为
otherfiledate
只使用一次,您可以避免声明和初始化它,如果FileDateTime(Filepath&“\”&MyFile)>zmasterdate,只需使用。2) ActiveSheet.Paste Destination:=工作表(“反射”)。范围(单元格(erow,2),单元格(erow,14))
可以是ActiveSheet.Paste Destination:=工作表(“反射”)。单元格(erow,2)
和excel将填充复制范围内的尽可能多的单元格。3) 如果Sheet1
是Worksheets(“Reflections”)
的话,你就可以在Sheet1中使用。。以
pattern 4)结束,Sheet1在哪里定义?这样,代码在找到otherfiledate>zmasterdate后就会停止。我如何告诉它继续并遍历文件夹中的每个文件?如果它停止,则会出现其他问题,我猜这与文件路径有关。这段代码确实循环遍历目录中的所有文件。文件路径应该有一个结尾。因为您在filedatetime检查中添加了一个\,所以我猜它现在不存在。