フォルダ内、更新日時の一番新しいファイルを取得したい
ユーザーが操作したファイルや、マクロで作成したファイルで最も新しいファイルを取得したい場合があります。
FileSystemObjectでも取得は可能ですが、FileDateTime関数で紹介します。
フォルダ内、更新日時の一番新しいファイルを取得するサンプルコード
’■指定フォルダ内で一番新しいファイル(Latest)を取得する Public Function Call_GetLatestFile(sPath As String, sExtension As String) As String Dim chkTime As Date Dim maxTime As Date Dim chkName As String Dim maxName As String sPath = Call_TruePath(sPath) '★ chkName = Dir(sPath & sExtension) maxTime = FileDateTime(sPath & chkName) maxName = chkName Do While chkName <> "" chkTime = FileDateTime(sPath & chkName) '■時間を比較し、既存より古ければ、ファイル名、ファイル更新時間を上書き If chkTime > maxTime Then maxTime = chkTime maxName = chkName End If chkName = Dir() Loop Call_GetLatestFile = maxName 'ファイル名の場合 'Call_GetLatestFile = sPath & maxName 'フルパス(パス&ファイル名)の場合 End Function
使い方
実際の使い方は以下です。
Public Sub sample() Dim sPath As String: sPath = "C:\vba" Dim sFile As String sFile = Call_GetLatestFile(sPath, "*") '全ての拡張子から一番古いファイルを取得 sFile = Call_GetLatestFile(sPath, "*.xls*") '.xlsを含むファイルから一番古いファイルを取得(.xls/.xlsx/.xlsm) End Sub
注意点
- 上記コードのみでは動きません。下記のパーツ化された処理も追加してください。
※コメント★部分の処理は別処理で動きます。
・指定パスの末尾に円マーク(\)付与する
コメント