0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ファイルの最終更新時間をファイル名に追加してコピーする

Posted at

課題

社内システムの夜間処理で特定のフォルダ特定のファイル名(日付スタンプを含まない)で自動作成されるデータファイルがある。ファイル名に日付を含まないので、更新されたかどうかはファイルの最終更新時間をチェックする必要がある。更新されたファイルはその日の業務に利用するため、ファイル名に日付をつけて、作業用のフォルダにコピーする。

処理

  1. 特定のフォルダ特定のファイル名のファイルがあることを確認する
  2. ファイルがない場合はメッセージを表示して処理を終了する
  3. ファイルがある場合は以下を行う
    1. ファイルの最終更新時間を確認する
    2. ファイルが24時間以内に更新されている場合は、ファイル名に日付スタンプを追加して作業用フォルダにコピーする. ただしファイルが既に存在する場合はメッセージを表示して処理を終了する
    3. ファイルが24時間以内に更新されていない場合は、メッセージを表示して処理を終了する

実装

事前準備

  • VBEの ツール→参照設定 から"Microsoft Scripting Runtime"を追加する

コード

Sub CheckAndCopyFile()

    Dim fso As FileSystemObject
    Dim strPath As String, strDestPath
    Dim f As File
    
    strPath = "C:\Users\user\Desktop\sample\src\data.csv"
    strDestPath = "C:\Users\user\Desktop\sample\dst\data_" & Format(Now, "yyyymmdd") & ".csv"
    
    Set fso = New FileSystemObject
    If Not fso.FileExists(strPath) Then
        MsgBox "File Does Not Exist: " & strPath
        Exit Sub
    End If
    
    Set f = fso.GetFile(strPath)
    If f.DateLastModified > Now - 1 Then
        If fso.FileExists(strDestPath) Then
            MsgBox "File Already Exists: " & strDestPath
            Exit Sub
        End If
        f.Copy strDestPath, False
        MsgBox "Done"
    Else
        MsgBox "File Is Outdated: " & Format(f.DateLastModified, "yyyy-mm-dd hh:mm:ss")
    End If
End Sub
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?