For each Next 構文
VBAセルレンジ処理に便利なFor Each Nextを用いたデータ処理の記事です。
状況
特定範囲セル内の数値に応じてセル背景を塗りつぶしたい
実施
セル背景色の取得
For Each構文を用いた連続範囲処理
If構文を用いた場合分け
セル背景色塗りつぶし
シート画像
セル内はRand()関数で数値を埋めました
- VBA記述
Sub Test() Dim Range1, P As Range Set Range1 = Range(Cells(3, 7), Cells(8, 12)) A = Cells(3,2).Interior.Color B = Cells(4,2).Interior.Color C = Cells(5,2).Interior.Color D = Cells(6,2).Interior.Color E = Cells(7,2).Interior.Color For Each P In Range1 If 0.8 <= P And P <= 1 then P.Interior.Color = A Elseif 0.6 <= P And P < 0.8 then P.Interior.Color = B Elseif 0.4 <= P And P < 0.6 then P.Interior.Color = C Elseif 0.2 <= P And P < 0.4 then P.Interior.Color = D Elseif 0 <= P And P < 0.2 then P.Interior.Color = E End If Next End Sub