LoginSignup
0
1

More than 3 years have passed since last update.

【メモ】Excel マクロで、フォルダ内のファイルを全て処理する

Last updated at Posted at 2020-11-08

※VBA,Excel初心者がメモとして書いた記事です。

・エクセルの「マクロの記録」で作った処理を、フォルダ内の全ブックに適応したい
1. 「マクロの記録」で作成した処理を、下記コードの「処理を追加」部分に記入して保存する。(xlsmファイル)
2. 保存したxlsmファイルを、処理したいブックが保存されているフォルダに移動する。
3. xlsmファイルを開いて、マクロを実行する。

Sub Macro_dir_files()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim file As Object
For Each file In fso.GetFolder(ThisWorkbook.Path).Files
    If file.Type = "Microsoft Excel ワークシート" Then
        With Workbooks.Open(file.Path)
            With .Worksheets(1)
                '処理を追加
            End With
        ' 保存してブックを閉じる場合、コメントアウトを外す
        ' .Close SaveChanges:=True
        End With
    End If
Next file
End Sub

・i.g.
「マクロの記録」で下記のコードを生成。

ActiveCell.FormulaR1C1 = "Hello World"
ActiveCell.Offset(1, 0).Range("A1").Select

下のように、書き換えて保存する。

Sub Macro_dir_files()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim file As Object
For Each file In fso.GetFolder(ThisWorkbook.Path).Files
    If file.Type = "Microsoft Excel ワークシート" Then
        With Workbooks.Open(file.Path)
            With .Worksheets(1)
                '処理を追加
                ActiveCell.FormulaR1C1 = "Hello World"
                ActiveCell.Offset(1, 0).Range("A1").Select
            End With
        ' 保存してブックを閉じる場合、コメントアウトを外す
        ' .Close SaveChanges:=True
        End With
    End If
Next file
End Sub
0
1
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
1