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 2023-08-08

概要

これを…
image.png
こうしたい。
image.png

やり方

参照設定に『Microsoft Excel 16.0 Object Library』追加。
image.png

サンプル
'Accessと同じフォルダーにある『tes.xlsx』が対象。
Dim file_path_ As String: file_path_ = CurrentProject.Path & "\tes.xlsx"

Dim excel_ As New Excel.Application
Dim excel_sheet_ As Excel.Worksheet

'バックグラウンドで起動。
excel_.Visible = False
excel_.UserControl = False
excel_.Workbooks.Open FileName:=file_path_

'一番左のシートのみを選択状態に。
Set excel_sheet_ = excel_.Worksheets(1)
excel_sheet_.Select Replace:=True

'1行目にフィルター追加。
'既にフィルターが付いていた場合はフィルターが外される。
'AutoFilterはトグル動作。
excel_sheet_.Rows(1).AutoFilter

'変更保存してエクセルファイル閉じてエクセル終了。
excel_.Workbooks(1).Close SaveChanges:=True
excel_.Quit

AutoFilterはトグル動作

前述のサンプルについて、既にフィルターが付いている状態のxlsxに対して行うと、フィルターが無しになります。

途中に空の列がある場合

前述のサンプルについて、下記のような空の列がある場合…
image.png

処理結果は下記。
image.png

参考サイトさん

バージョン

Microsoft Windows [Version 10.0.19045.3271]
Microsoft Access for Microsoft 365 MSO (バージョン 2307 ビルド 16.0.16626.20110) 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?