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でエクセルファイル内に特定の名前のシートが存在するか判定

Posted at

やり方

参照設定に下記追加。
image.png

サンプル
'フォーム上に『btn_1』という名前のオブジェクトがある前提。
'そのクリックイベント。
Private Sub btn_1_Click()

    Dim excel_ As New Excel.Application
    
    'バックグラウンドで起動
    excel_.Visible = False
    excel_.UserControl = False
    
    'Accessファイルと同じフォルダーにあるtest.xlsxが対象。
    excel_.Workbooks.Open FileName:=CurrentProject.Path & "\test.xlsx"
    
    'Excel.Applicationに『シート存在チェック関数』といったものは無い。
    'シート一覧をループして一つ一つ名前を取得して判定が必要。

    'excel_.WorksheetsはFor Eachのインターフェース無いのでForでまわす。
    Dim i_ As Long
    For i_ = 1 To excel_.Worksheets.Count
        'excel_.Worksheets(i_)が非表示シートであっても例外にならない。
        'また、非表示シートだからとって『取得したシート名が空やNULL』といったこともない。
        '(シートが非表示かどうかは気にしなくてOK)
        If excel_.Worksheets(i_).Name = "あ" Then
            MsgBox "あるよ", vbInformation
        End If
    Next
    
    'エクセルは保存せずに閉じる。
    excel_.Workbooks(1).Close SaveChanges:=False
    excel_.Quit
    
End Sub

参考サイトさん

バージョン

Windows 10 Pro 22H2 19045.2965
Microsoft Access for Microsoft 365 MSO (バージョン 2304 ビルド 16.0.16327.20200) 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?