#author("2023-07-23T19:40:07+09:00","","")
#navi(../)
* Excelブックのシート数をシート名を取得するサンプル [#ce40ce3b]
Excelブック上にあるシートの情報を取得するVBAサンプルコードになります。~
シート数の取得、シート名の取得のサンプルコードを以下に記します。
#contents
#htmlinsert(office_ads_top.html)
* 関連サイト [#a617fd7a]
-[[Microsoft: Worksheets.Count プロパティ (Excel)>https://learn.microsoft.com/ja-jp/office/vba/api/excel.worksheets.count]]
-[[Microsoft: Worksheets オブジェクト (Excel)>https://learn.microsoft.com/ja-jp/office/vba/api/excel.worksheets]]
* 動作確認環境 [#p4c9d5ac]
- Windows 10 バージョン 22H2
- Microsoft® Excel® for Microsoft 365 MSO (バージョン 2305 ビルド 16.0.16501.20074) 32 ビット
* 動作確認シート [#uc726822]
以下のキャプチャの通り、Sheet1, Sheet2, Sheet3, Sheet4, Sheet5 計5つのシートを用意しました。
#br
#ref(01.png)
#br
* VBAサンプルコード [#s9339d76]
GetWorksheetsCount()関数では、Excelブックにあるシート数を取得しシート数を返却します。~
Test()関数では、GetWorksheetsCount()関数の呼び出しと For Each と インデックス指定でシート名を取得するサンプルコードになります。
Option Explicit
Function GetWorksheetsCount() As Integer
GetWorksheetsCount = Worksheets.Count
End Function
Sub Test()
MsgBox ("シート数:" & GetWorksheetsCount)
'For Each で取得
Dim ws As Worksheet
For Each ws In Worksheets
MsgBox ws.Name
Next
'インデックス値で取得
Dim i As Integer
For i = 1 To GetWorksheetsCount
MsgBox Worksheets(i).Name
Next i
End Sub
* 実行結果 [#w21cbfa9]
シート数の取得とシート名を取得するサンプルを実行した時のキャプチャです。
** シート数取得 GetWorksheetsCount [#w89c98db]
#br
#ref(02.png)
#br
** シート名取得 For Each .. Next [#j8ff10c1]
#br
&ref(11.png); &ref(12.png); &ref(13.png); &ref(14.png); &ref(15.png);
#br
** シート名取得 For .. Worksheets(index) .. Next [#i01e0aa8]
#br
&ref(11.png); &ref(12.png); &ref(13.png); &ref(14.png); &ref(15.png);
#br
以上、Excel VBAを使ってシート数とシート名を取得するサンプルコードでした。
#htmlinsert(office_ads_btm.html)