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?

More than 1 year has passed since last update.

AccessのVBAでファイル数カウント(特定の拡張子に絞ったカウントについても)

Last updated at Posted at 2022-11-05

FileSystemObjectを使用

下記の理由がある為、Dir()は使わずFileSystemObjectを使います。

参照設定

FileSystemObjectを使えるようにMicrosoft Scripting Runtimeを参照。

image.png

image.png

Microsoft Scripting Runtimeの参照設定をしなくてもFileSystemObjectを使う方法はあります。
ですが、下記のようなメリットがある為、個人的には参照設定して使うのがおススメです。

  • コンパイルチェックで入力ミスをあぶりだせる
  • Ctrl + スペースで候補が出てきてコーディングが楽

やり方(とにかく全ファイル)

Dim fso_ As New Scripting.FileSystemObject
Debug.Print fso_.GetFolder("フォルダーパス").Files.Count

GetFolder()について、フォルダーパスの末尾に『\』が付いても、付いていなくても、どちらでも動作に変わりは無い。

存在しないフォルダーを指定した場合は下記の例外。

実行時エラー76
パスが見つかりません。

image.png

やり方(特定の拡張子のファイル)

Dim fso_ As New Scripting.FileSystemObject
Dim file_ As Scripting.File
Dim count_ As Long: count_ = 0
    
For Each file_ In fso_.GetFolder("フォルダーパス").Files
    If fso_.GetExtensionName(file_) = "csv" Then
        count_ = count_ + 1
    End If
Next
    
Debug.Print count_

GetExtensionName() で取得できる文字列に『.』は付かない。

蛇足

特定の拡張子のファイル数を取りたい時、For Each回すのは若干面倒。
ワイルドカードでサクッとカウント取る方法が見つからなかった…。

でもあらかじめFor Eachで作っておくと、『ファイル作成日』や『その他の属性』によって条件分岐したい、なんて要件が出てきた時は楽。

参考サイトさん

バージョン

Windows 10 Pro 21H2 OSビルド 19044.2130
Microsoft Access for Microsoft 365 MSO (バージョン 2209 ビルド 16.0.15726.20068) 32 ビット

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?