« RangeオブジェクトにCellsプロパティを使う | トップページ | iCalendar形式のファイルをExcelで生成する1 »

2018年11月14日 (水)

Use Cells property for Range object

For referring to a certain cell
You can use both the Range property and the Cells property.

The value of cell A1 of the active sheet
can be set to 1
by the following two methods.

ActiveSheet.Range("A1") = 1
ActiveSheet.Cells(1, 1) = 1

With the Range property,
Since it must be specified in A1 format
In the For statement, the Range property is hard to use.

On the other hand, the Cells property
You can specify rows and columns with numbers
It's easy to use in For statements.

I have separately used Range properties and Cells properties
for the reasons mentioned above.

Actually,
Cells property can also be used for Range object.
See also: "Cells property" in MSDN site(Japanese only)

For example, use as follows.

Range("B2:D6").Cells(2, 2) = 2

The above code sets the value of cell C3 of the active sheet to 2.

Vba20180729a
In this usage The Cells property specifies the cell C3
at (2, 2) relative to the upper left cell
of the range of the Range object.
(The range of the Range object is
within the red frame in the above figure.)

This usage is quite useful.

Using the Cells property for the Range object,
It can be used to put values
in each cell contained in the Range object.

The number of lows and columns of the Range object
can be obtained with the following codes.

Range("B2:D6").Rows.Count
Range("B2:D6").Columns.Count

It is used for index of For statement.

Code here

Code that uses the Cells property of the Range object:

Sub macro180729a()
'How to use the Cells property
'for Range object

    Dim i As Integer, j As Integer
    Dim Rng1 As Range
   
    Set Rng1 = Range("B2:D6")
   
    For i = 1 To Rng1.Rows.Count
        For j = 1 To Rng1.Columns.Count
            Rng1.Cells(i, j) = i & ", " & j
        Next j
    Next i
   
End Sub

Result:
Vba20180729b

A value was entered in the cell of the range "B2: D6" of the range object.

|

« RangeオブジェクトにCellsプロパティを使う | トップページ | iCalendar形式のファイルをExcelで生成する1 »

コメント

この記事へのコメントは終了しました。

トラックバック


この記事へのトラックバック一覧です: Use Cells property for Range object:

« RangeオブジェクトにCellsプロパティを使う | トップページ | iCalendar形式のファイルをExcelで生成する1 »