
下記図のように指定フォルダーの下にあるサブフォルダーから最新のサブフォルダーパスを抽出する方法を紹介します。



フォルダー名ではなく最新更新日時で抽出したいときに便利だよ!
コピペして使ってね!




目次
指定フォルダーから最新フォルダーを自動抽出 サンプル
任意のフォルダー下の最新のサブフォルダのパスを抽出したい
今回はファイルシステムオブジェクト(FileSystemObject = FSO)を活用して、フォルダーを選択し、その中にある最新サブフォルダーの最新パスを抽出するサンプルになります。
Sub NewestFolder_PickUp()
Application.ScreenUpdating = False
Dim Folder_Path As String
MsgBox "最新フォルダパスを自動抽出するよ!フォルダを選択してね( ー`дー´)"
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = True Then
Folder_Path = .SelectedItems(1)
Else
MsgBox "フォルダが正しく選択されなかったので終了します(#^ω^)"
Exit Sub
End If
End With
Dim FSO As Object, Folder As Object, Fl As Object
Set FSO = CreateObject("Scripting.FIleSystemObject")
Set Folder = FSO.GetFolder(Folder_Path)
Dim NewestFolder As String
Dim MaxTime As Date
For Each Fl In Folder.SubFolders
If Fl.DateLastModified > MaxTime Then
MaxTime = Fl.DateLastModified
NewestFolder = Fl.PATH
End If
Next
MsgBox "最新フォルダーのPathは " & vbCrLf & NewestFolder & vbCrLf & "です(^o^)"
End Sub
FSOを使用するにはその下準備として「Microsoft Scripting Runtime」への参照設定を行う必要があります。
1.ツールをクリック
2.[参照設定]をクリック
3.参照可能なライブラリファイルから「Microsoft Scripting Runtime」をクリックしチェックマークをつける
4.[OK]をクリック




まとめ
このサンプルを活用いただけると、サブフォルダー名に関わらず最新更新日時のパスを抽出することができます。
この記事がミス撲滅や生産性向上につながるととても嬉しいです。
VBA初級から抜け出すための知恵と、実務で活用できるスキルが学べる1冊です!激しくオススメ!


コメント