0
1

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 5 years have passed since last update.

[Excelマクロ] Cellsでセル指定できるのはアクティブシート内だけかよ,という話

Last updated at Posted at 2019-10-29

データの解析で楽するためのマクロを作ろうとしたら,しょーもないところで躓いてしまった.
まとめておきます.

何をしたかったか

Sheet1がこんな感じになっているとする.
hoge1.PNG

このとき,各条件での「Current1」だけをSheet2にまとめたい.
こんな感じ↓↓↓
hoge2.PNG

この場合は数が少ないから手でできるけれど,データが増えてくるとかなり面倒.

コピーするだけでは?

以前こちらのサイトを拝見し,「は~すご」と思ったので,コピーは以下のように書くことにしていた.

Worksheets("Sheet2").Range("C5:C26").Value = Worksheets("Sheet1").Range("C5:C26").Value

さて,今回は一定間隔で並ぶデータをコピーしたい.
上記ダミーデータでは3条件だが,条件数は今後変わるかもなので,これを変数にしてFor文で回せるようにしよう.それならば,Cells(row,column)でセルを指定するのが何かと都合が良い.

というわけでコピーのところを以下のように書き換え.

Worksheets("Sheet2").Range(Cells(5,3), Cells(26,3)).Value = Worksheets("Sheet1").Range(Cells(5,3), Cells(26,3)).Value

"C5:C26" を Cells(5,3), Cells(26,3) に書き換えただけですね.実際はここに変数を入れてます.

エラー吐く

しかし,上記コードでは思ったように動かず.
hoge3.PNG

調べたら,どうもCellsでセル指定できるのはアクティブシート内だけのようだ.
この情報にたどり着くまでにえらい時間をかけてしまった...

解決策

こちらのサイトのお世話になりました.

結論を言うと,Cellsの上位のオブジェクト式を省略せずに書けば動きます.
是非上記サイトもご参照ください.

Worksheets("Sheet2").Range(Sheets("Sheet2").Cells(5,3), Sheets("Sheet2").Cells(26,3)).Value = Worksheets("Sheet1").Range(Sheets("Sheet1").Cells(5,3), Sheets("Sheet1").Cells(26,3)).Value

以上!

Reference

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?