0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

指定フォルダ内の特定アイテムを検索しリスト化するVBA

Posted at

ファイルのリスト化が面倒くさかったから作ったVBAのメモ用記事

エクセルファイルを開いたら、次の画面が表示される
image.png
まず、ほしいアイテムが入っているフォルダのフルパスをShift+右クリックで取得し、フォルダの欄にコピペする。なお、フォルダを空欄にした場合はこのエクセルが保管されているフォルダがデフォルトパスとなる。
次にファイル検索条件にほしいアイテムのファイル名のキーワードを入れる。拡張子で検索するなら
txt』や『.txt』、キーワードで検索するなら『(キーワード)』や『(キーワード)』など。
例として
image.png
のようにtxtをリスト化にしたい場合は、ファイル検索条件の欄に『
.txt』を入力し
image.png
ファイルリスト作成をクリックすると
image.png
が得られる。

以下、VBAのソースコードのメモ

このVBAは3つのサブプロシージャによって構成されるが、特に分ける意味はないのでクラスオブジェクトのシート1に書き込んだものとする。

一々オブジェクトの定義が面倒くさいので、

Dim twb(5) As Object
Sub ob()'シートオブジェクトの略称を定義
For i = 1 To Worksheets.Count
Set twb(i) = ThisWorkbook.Worksheets(i).Cells
Next
'オブジェクトの略称を定義
End Sub

で略称の定義をしておく。用途によってシートまででも良さげ。

Sub dataexp() 'ファイルリストを作成 Dim pt, fkw, fnm, fpt As String Call ob 'シートオブジェクトの略称を呼び出す pt = twb(1).Cells(3, 3) If Len(pt) < 1 Then pt = ThisWorkbook.Path End If 'フォルダパスの定義。未定義の場合はこのエクセルファイルの格納フォルダがデフォルトパスとなる fkw = Dir(pt & "\" & Cells(3, 1)) i = 1 Do While fkw <> "" twb(1).Cells(5 + i, 3) = fkw fkw = Dir() i=i+1 Loop '条件を満たすファイルのパスを取得する End Sub Sub dataexp2() 'ファイルリストをリセット Call ob twb(1).Range("C6").CurrentRegion.ClearContents End Sub
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?