出題内容
画像のようにB2から始まる表があります。
B列×C列を計算した値をD列に入れ、通貨\のカンマ編集で表示してください。
ただしB列またはC列が空欄の場合は空欄表示にしてください。
例.D2にはB3×C3の計算結果の値を「\234,099」で表示、D5は空欄
自分の回答
Dim LastRow As Long
Dim i As LongLastRow = Cells(Rows.Count, 2).End(xlUp).Row
For i = 3 To LastRow
If Cells(i, 2) = "" Or Cells(i, 3) = "" Then
Else
Cells(i, 4).Value = Cells(i, 2) * Cells(i, 3)
Cells(i, 4).NumberFormatLocal = "¥#,##0"
Next i
Cells(Rows.count,2).End(xlUp).Rowで最終行を求めてループさせる。
Cells(i,2)とCells(i,3)が空欄でなければCells(i,2)とCells(i,3)をかけて書式設定をする。
今回は2列目に最後までデータが入っているが、データがかけてしまうと列によって最終行が変わってしまう。
解説
CurrentRegion.Rows.Countとすると表の範囲の行数を取得することができる。
For i = 3 To Range("B2").CurrentRegion.Rows.Count + 1
If Cells(i, 2) = "" Or Cells(i, 3) = "" Then
Cells(i, 4) = ""
Else
Cells(i, 4) = Cells(i, 2) * Cells(i, 3)
End If
Next
Columns("D").NumberFormatLocal = "¥#,##0"