VBAでワークシート選択する際に
いくつか方法があります!
最近使い分ける場面があったので
備忘録として残しておこうと思います!
エクセルシートをインデックスで指定
左から何番目(インデックス)のシートか?でシート指定。
マクロ実行しているシートをインデックスで指定する場合
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dim ws As WorkSheet | |
Set ws = ThisWorkbook.Sheets(1) |
これは一番左のシートを指定しています。
注意
シートの順番が変わるとインデックスも変更が必要
ですので確実にシートの順番を変えない!
という前提で使うといいと思います!
エクセルシートを名前で指定
その名の通りシート名でシートを指定。
マクロ実行しているシートをインデックスで指定する場合
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dim ws As Worksheet | |
Set ws = ThisWorkbook.Sheets("Sheet1") |
これは「Sheet1」という名前のシートを指定しています。
注意
シートの名前が変わると指定した名前も変更が必要
ですのでシート名を変えない!
という前提で使うといいと思います!
エクセルシートをオブジェクト名で指定
社内の他の開発者のコードを見て発見!
僕はコレをお勧めします!

シートのオブジェクト名を上図の様に変更してみます!
もともと
・オブジェクト名:Sheet1
・シート名:Sheet1
だったので
・オブジェクト名:sht1
と変更しました!
そうするとこのシートの指定は「sht1」で直接表せます!
例えばこのシートのA1セルの値を取得する場合
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dim s As String | |
s = sht1.Range("A1").Value |
ポイント
シートの順番・名前の変更に影響されない
今のところこの方法で開発する事が多いです!
是非参考にしてみてください!