2016-04-05 4 views
1

フォルダを経由するコードを書いたので、文書を開き、情報をコピーし、別の場所にあるマスターファイルに貼り付けます。私が抱えている問題は、最後のマスターファイルが変更された日付を他のフォルダー内の文書と比較するためにif、elseステートメントを追加したいということです。 if文を満たしていないときは、ループでその文書をスキップして次の文書の比較を続けます。これを進める方法がわからない場合は、コードを以下に示すことができます。VBA:doループ内のif/elseステートメントを継続する方法を教えてください

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

サイドノートでは、コードの途中でサブを終了することはできません。代わりに 'exit sub'を実行する必要があります。 'End Sub'はサブルーチンの終わりを示しています –

+0

いくつかの有益なメモがあります:1)' otherfiledate 'は宣言と初期化を避けて' if FileDateTime(Filepath& "\"&MyFile)> zmasterdate'とする。 2) 'ActiveSheet.Paste Destination:=ワークシート(" Reflections ")。Range(Cells(erow、2)、Cells(erow、14))'は単純に 'ActiveSheet.Paste Destination:= Worksheets(" Reflections ")です。セル(erow、2) 'とExcelはコピーされた範囲と同じ数のセルを埋めるでしょう。 3) 'Sheet1'は' Worksheets( "Reflections") 'でなければなりません。そして、' Sheet1 .. End With'パターンと一緒に行くことができます。 – user3598756

答えて

1

すでにチェックを行っているので、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 
+0

これを実行すると、コードはotherfiledate> zmasterdateを見つけると停止します。それを継続してフォルダ内のすべてのファイルを調べるにはどうすればよいですか? –

+0

それは停止している場合、いくつかの他の問題があり、私はそれがFilePathと関係があると推測しています。このコードは、ディレクトリ内のすべてのファイルをループします。 FilePathの末尾には\が必要です。今のところ、私はあなたがfiledatetimeチェックに\を追加してからではないと推測しています。 – Sorceri

+0

実際にあなたは正しいです。それはありがとうございました! –

関連する問題