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?

【Excel VBA】FileLen関数|ファイルサイズを取得する方法と注意点

0
Last updated at Posted at 2025-08-07

この記事ではFileLen関数の使い方と注意点について解説します。
他のよく使うVBA関数一覧はこちら。

FileLen関数の使い方と注意点

FileLen関数は、指定したファイルのバイトサイズを取得するための関数です。
ファイルの存在確認後に、容量チェックやログファイルのサイズ管理などで活用されます。

FileLen関数はファイルが存在しないとエラーになるため、事前にDir()などで存在確認を行うのが安全です。

構文

FileLen(ファイルパス)
  • ファイルパス : フルパスまたは相対パスで指定します。
  • 戻り値 : ファイルサイズ(バイト単位、Long型)を返します。

使用例

ファイルサイズを取得する基本例

Sub Sample()
    Dim size As Long
    size = FileLen("C:\Temp\sample.txt")
    Debug.Print size & " バイト"
End Sub

▶ 出力結果

88562 バイト

ファイルの存在チェック後、ファイルサイズを取得

ファイルが存在しない場合、FileLen関数はエラーになります。
error_53.png

特定のファイル名を指定する場合、ファイルサイズを取得する前にファイルが存在するか確認しましょう。

Sub Sample()
    Dim FilePath As String
    Dim size As Long

    FilePath = "C:\Temp\sample.txt"

    If Dir(FilePath) <> "" Then
        size = FileLen(FilePath)
        Debug.Print "サイズ: " & size & " バイト"
    Else
        Debug.Print "ファイルが存在しません"
    End If
End Sub

▶ 出力結果

サイズ: 88562 バイト

複数ファイルのサイズをまとめて出力

Sub Sample()
    Dim FolderPath As String
    Dim FileName As String
    Dim row As Long

    FolderPath = "C:\Temp\"
    FileName = Dir(FolderPath & "*.txt")
    row = 1

    Do While FileName <> ""
        Cells(row, 1).Value = FileName
        Cells(row, 2).Value = FileLen(FolderPath & FileName)
        row = row + 1
        FileName = Dir()
    Loop
End Sub

▶ 出力結果
sample03.png

ファイルサイズが一定以上か判定する

Sub Sample()
    Dim FolderPath As String
    Dim FileName As String
    Dim row As Long

    FolderPath = "C:\Temp\"
    FileName = Dir(FolderPath & "*.txt")
    row = 1

    Do While FileName <> ""
        Cells(row, 1).Value = FileName
        Cells(row, 2).Value = FileLen(FolderPath & FileName)
        If FileLen(FolderPath & FileName) > 100000 Then
            With Cells(row, 3)
                .Value = "ファイルサイズが100KBを超えています"
                .Interior.Color = RGB(255, 0, 0)
            End With
        End If
        row = row + 1
        FileName = Dir()
    Loop
End Sub

▶ 出力結果
sample04.png

⚠️注意

ファイルが存在しないとエラー

存在しないファイルを指定すると**実行時エラー53(ファイルが見つかりません)**になります。
error_53.png

特定のファイル名を指定する場合、ファイルサイズを取得する前にファイルが存在するか確認しましょう。

ディレクトリやフォルダを指定するとエラー

FileLenはファイル専用です。フォルダを指定すると**実行時エラー53(ファイルが見つかりません)**になります。

Sub Sample()
    Dim size As Long
    size = FileLen("C:\Temp\")
    Debug.Print size & " バイト"
End Sub

▶ 出力結果
error_53.png

その他のVBA関数

【Excel VBA】VBAでよく使う関数一覧&基本の使い方

参考リンク

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?