RangeとCellsって似ているようで似ていない…
この2つの使い方について違いをメモ。
Rangeの使い方の基本は以下ですね。
' セルA1に10を出力 Range("A1").Value = 10 ' B1:C3の範囲内のセルに20を出力する Range("B1:C3").Value = 20 ' 「Data」と名前定義した範囲に30を出力する Range("Data").Value = 30
Rangeは上記のように操作対象の範囲が決まっているときの使用が適していますね。
次はCellsの使い方。
' 1行目1列目のセルに10を出力する Cells(1, 1).Value = 10 ' 変数で指定したセルに20を出力する Dim rowIndex As Long Dim colIndex As Long rowIndex = 1 colIndex = 2 Cells(rowIndex, colIndex).Value = 20
CellsはRangeと異なり、範囲ではなく特定のセルを指定します。
変数も使用できるので可変の場合はCellsの使用が適しています。
範囲が可変だけどRangeを使いたいときは
Cellsと合わせて使うこともできます。
以下、変数を使って範囲を選択するサンプルです。
Dim startRow As Long Dim startCol As Long Dim endRow As Long Dim endCol As Long startRow = 1 startCol = 1 endRow = 2 endCol = 2 ' 指定された開始と終了の範囲を選択する Range(Cells(startRow, startCol), Cells(endRow, endCol)).Select
上記の方法でループでの対応なども可能ですね。