VBAで条件付書式設定方法

このQ&Aのポイント
  • VBAを使ってセルの条件付書式を設定する方法について教えてください。
  • 実行時にアクティブセルにならないコーディング方法や、より合理的でシンプルな方法があれば教えてください。
  • エラーや行ズレが発生して困っています。解決策をお願いします。
回答を見る
  • ベストアンサー

VBAで条件付書式設定方法

次の内容の件です Dim wArray As Variant Dim wI As Integer ' セルA3:K3の条件付書式設定 A3の設定:A3=B3は黒,A3<B3は緑,A3>B3は赤,以降同様に wArray = Array(, "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L") For wI = 1 To UBound(wArray) - 1    Sheets("Sheet1").Cells(3, wI).Select    Selection.FormatConditions.Delete    Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$" & wArray(wI) & "3=$" & wArray(wI + 1) & "3"    With Selection.FormatConditions(1).Font      .Bold = False      .Italic = False      .ColorIndex = xlAutomatic    End With    Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$" & wArray(wI) & "3<$" & wArray(wI + 1) & "3"    With Selection.FormatConditions(2).Font      .Bold = False      .Italic = False      .ColorIndex = 10    End With    Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$" & wArray(wI) & "3>$" & wArray(wI + 1) & "3"    With Selection.FormatConditions(3).Font      .Bold = False      .Italic = False      .ColorIndex = 3    End With Next wI 実行時にアクティブセルにならないコーディング方法は? また、もっと合理的な、シンプルな方法はないでしょうか? いろいろと、やってみましたが、エラーとか行ズレとなり困っています よろしくご教示ください

質問者が選んだベストアンサー

  • ベストアンサー
  • merlionXX
  • ベストアンサー率48% (1930/4007)
回答No.7

ANo1-6 merlionXXです。 ANo6のでも大丈夫と思いますが書き方に変なところがありましたので再修正します。 Sub test04()   Dim myC As Range   Set myC = ActiveCell   With Sheets("Sheet1").Range("A3:L3")     .Cells(1).Activate     .FormatConditions.Delete     .FormatConditions.Add Type:=xlExpression, Formula1:="=A3=B3"     With .FormatConditions(1).Font       .ColorIndex = xlAutomatic     End With     .FormatConditions.Add Type:=xlExpression, Formula1:="=A3<B3"     With .FormatConditions(2).Font       .ColorIndex = 10     End With     .FormatConditions.Add Type:=xlExpression, Formula1:="=A3>B3"     With .FormatConditions(3).Font       .ColorIndex = 3     End With   End With   myC.Activate End Sub

myt16n
質問者

お礼

ていねいにありがとうございました ステップの違いを確認・テストしてマスターしていきます

その他の回答 (6)

  • merlionXX
  • ベストアンサー率48% (1930/4007)
回答No.6

> merlionさんのとおり実行しましたが、期待する結果が得られませんでした 失礼しました。 以下で再度お試しください。 Sub test03()   Dim myC As Range   Set myC = ActiveCell   With Sheets("Sheet1").Range("A3:L3")     .Range("A3").Activate     .FormatConditions.Delete     .FormatConditions.Add Type:=xlExpression, Formula1:="=A$3=B$3"     With .FormatConditions(1).Font       .ColorIndex = xlAutomatic     End With     .FormatConditions.Add Type:=xlExpression, Formula1:="=A$3<B$3"     With .FormatConditions(2).Font       .ColorIndex = 10     End With     .FormatConditions.Add Type:=xlExpression, Formula1:="=A$3>B$3"     With .FormatConditions(3).Font       .ColorIndex = 3     End With   End With   myC.Activate End Sub

myt16n
質問者

お礼

ありがとうございました きれいで無理・無駄がありませんね activate と select を再認識し、なるほどと感じ入った次第です いじくりでなく、基礎を確認することが大事なことがよくわかりました たいへんお世話になりました

  • mitarashi
  • ベストアンサー率59% (574/965)
回答No.5

#2です。もうひとひねりしてみました。ご参考まで。 Sub test() Dim formulaArray As Variant, colorArray As Variant Dim i As Long formulaArray = Array("=RC=RC[+1]", "=RC<RC[+1]", "=RC>RC[+1]") colorArray = Array(xlAutomatic, 10, 3) With Sheets("Sheet1").Range("A3:K3") .FormatConditions.Delete For i = 1 To 3 .FormatConditions.Add Type:=xlExpression, Formula1:=formulaArray(i - 1) .FormatConditions(i).Font.colorIndex = colorArray(i - 1) Next i End With End Sub

myt16n
質問者

お礼

横を縦にしたようなものですね 恐れ入ります ありがとうございました

  • Wendy02
  • ベストアンサー率57% (3570/6232)
回答No.4

私は、「合理的」とか良く分かりませんが、可読性を犠牲にするなら、アリかもしれません。ただ、こういうのは苦手です。 Sub ConditionPro1()  Dim a As String, b As String  With Worksheets("Sheet1").Range("A3").Resize(1, 12)   a = "=" & "RC": b = "RC[1]"   .FormatConditions.Delete   With .FormatConditions.Add(2, 0, a & "=" & b, 0)    .Font.ColorIndex = xlAutomatic   End With   With .FormatConditions.Add(2, 0, a & "<" & b, 0)    .Font.ColorIndex = 10   End With   With .FormatConditions.Add(2, 0, a & ">" & b, 0)    .Font.ColorIndex = 3   End With  End With End Sub

myt16n
質問者

お礼

ご回答ありがうございました Wendy02さんの言われる可読性とシンプルが最優先ですね 私の提示したものは、「For文」しか頭になくそれで配列を ほんとにコテコテですね ご回答の引数形式は難解に感じる位ですから 今後もよろしくお願いします

  • tom04
  • ベストアンサー率49% (2537/5117)
回答No.3

こんばんは! 一例です Sub test() Range(Cells(3, 1), Cells(3, 12)).Font.ColorIndex = 0 Dim j As Long For j = 1 To 11 If Cells(3, j) = Cells(3, j + 1) Then Cells(3, j).Font.ColorIndex = xlAutomatic ElseIf Cells(3, j) < Cells(3, j + 1) Then Cells(3, j).Font.ColorIndex = 10 Else Cells(3, j).Font.ColorIndex = 3 End If Next j End Sub こんな感じではどうでしょうか? 的外れならごめんなさいね。m(__)m

myt16n
質問者

お礼

ご回答ありがうございました 今回、各種の書式エリアにデータを何回も展開する環境でしたので 今後、利用していきたいと参考になりました 今後もよろしくお願いします

  • mitarashi
  • ベストアンサー率59% (574/965)
回答No.2

相対アドレスになってしまいますが、支障があるでしょうか? Sub test() With Sheets("Sheet1").Range("A3:K3") .FormatConditions.Delete .FormatConditions.Add Type:=xlExpression, Formula1:="=RC=RC[+1]" With .FormatConditions(1).Font .Bold = False .Italic = False .ColorIndex = xlAutomatic End With .FormatConditions.Add Type:=xlExpression, Formula1:="=RC<RC[+1]" With .FormatConditions(2).Font .Bold = False .Italic = False .ColorIndex = 10 End With .FormatConditions.Add Type:=xlExpression, Formula1:="=RC>RC[+1]" With .FormatConditions(3).Font .Bold = False .Italic = False .ColorIndex = 3 End With End With End Sub

myt16n
質問者

お礼

ご回答ありがうございました 相対アドレスはなかなか使うことがありませんでした すっきりしていて大変参考になりました 今回、相対アドレス利用関数を調べて勉強します 今後もよろしくお願いします

  • merlionXX
  • ベストアンサー率48% (1930/4007)
回答No.1

> もっと合理的な、シンプルな方法はないでしょうか? Sub test02()   With Sheets("Sheet1").Range("A3:L3")      .FormatConditions.Delete      .FormatConditions.Add Type:=xlExpression, Formula1:="=A$3=B$3"      With .FormatConditions(1).Font        .ColorIndex = xlAutomatic      End With      .FormatConditions.Add Type:=xlExpression, Formula1:="=A$3<B$3"      With .FormatConditions(2).Font        .ColorIndex = 10      End With      .FormatConditions.Add Type:=xlExpression, Formula1:="=A$3>B$3"      With .FormatConditions(3).Font        .ColorIndex = 3      End With   End With End Sub

myt16n
質問者

お礼

早速のご回答ありがとうございました ほんの初心者で、基礎をマスターしないまま、知り得た知識をあっちこっち組み合わせて利用しているところです プログラムをご覧になってお分かりのことと思います  さて、ご親切なご回答にたいへん感謝いたしておりますとともに、各種方法があることにVBAの多様性をつくづく感じ入るところです  今後も機会があると思いますのでよろしくお願いします merlionさんのとおり実行しましたが、期待する結果が得られませんでした すっきりして無駄のないコーディングたいへん参考になりました できましたら、ご検証のうえ再度お知らせいただきたいのですが よろしくお願いします

関連するQ&A

  • 複数の条件付書式

    B列に1~5までに数字がランダムにはいっています。 条件は ・B列が空白ならA列は無色 ・B列が1ならA列は赤 ・B列が2ならA列は青 ・B列が3ならA列は黄色 ・B列が4ならA列は緑 というのをマクロで行ないたいです。 自分で記録して Sub Macro32() Columns("A:A").Select Selection.FormatConditions.Delete Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=B1=""""" Selection.FormatConditions(1).Interior.Pattern = xlNone Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=B1=1" Selection.FormatConditions(2).Interior.ColorIndex = 38 Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=B1=2" Selection.FormatConditions(3).Interior.ColorIndex = 40 End Sub 4つ目に Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=B1=3" Selection.FormatConditions(4).Interior.ColorIndex = 32 とするとエラーになります。 3つ以上の条件付書式の書き方を教えてください。 あとこの構文のSelectionはwithで省略できますか? よろしくお願いします。

  • excel2000 条件付書式5つ

    A1~J10に100個の数値があり、 行ごとの1位~5位にそれぞれ書式を あたえます。 マクロの記録機能を使って1位~3位を。 その後別で4位・5位を記録し、くっつけて みました。 つけたい書式は 以下のマクロの通りのセルのパターン・フォントの色です。 以下は記録したものをくっつけてつくったマクロです。 動作しません。 Sub 条件付書式5つ() Selection.FormatConditions.Delete Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ Formula1:="=LARGE($A1:$J1,1)" Selection.FormatConditions(1).Font.ColorIndex = 2 Selection.FormatConditions(1).Interior.ColorIndex = 1 Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ Formula1:="=LARGE($A1:$J1,2)" Selection.FormatConditions(2).Font.ColorIndex = 2 Selection.FormatConditions(2).Interior.ColorIndex = 16 Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ Formula1:="=LARGE($A1:$J1,3)" Selection.FormatConditions(3).Interior.ColorIndex = 15 Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ Formula1:="=LARGE($A1:$J1,4)" Selection.FormatConditions(4).Font.ColorIndex = 2 Selection.FormatConditions(4).Interior.ColorIndex = 3 Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _ Formula1:="=LARGE($A1:$J1,5)" Selection.FormatConditions(5).Font.ColorIndex = xlAutomatic Selection.FormatConditions(5).Interior.ColorIndex = 38 End Sub 初心者のためどうしたらいいのかまったく わかりません。 どうぞお願いします。

  • Excel2003 VBAにて条件付き書式のマクロを書きたいのですが、

    Excel2003 VBAにて条件付き書式のマクロを書きたいのですが、どうも上手くいきません。 1列おき(C列、E列、G列・・・)に条件付き書式を設定し、 条件は、 ・セルの値が”0”より大きい場合はフォント”赤”で表示。 ・セルの値が”0”より小さい場合はフォント”緑”で表示。 としたいと思いマクロを組んでみました。 Sub Color() Dim j, j0 Dim x Worksheets("sheet1").Active Application.ScreenUpdating = False j0 = 3 j = 300 For x = 3 To 100 Step 2 Range(.Cells(j0, x), .Cells(j, x)).Select Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="0" Selection.FormatConditions(1).Font.ColorIndex = 3 Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _ Formula1:="0" Selection.FormatConditions(2).Font.ColorIndex = 10 Next Application.ScreenUpdating = True End Sub デバックでステップインしていくと、ここで実行時エラー1004 アプリケーション定義またはオブジェクト定義のエラーです。がでます。 Selection.FormatConditions(1).Font.ColorIndex = 3 -------------------------------------------------------------------------------------- Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="0" Selection.FormatConditions(1).Font.ColorIndex = 3 Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _ Formula1:="0" Selection.FormatConditions(2).Font.ColorIndex = 10 -------------------------------------------------------------------------------------- この間は、マクロの自動記録で書かれてるので間違ってはいないハズなのですが、、、 お知恵を下さい。 よろしくお願いします。

  • EXCELでマクロの記録を繰り返して

    EXCELでマクロの記録を繰り返して重複した行は分かる範囲でまとめたのですが、もう少しまとめられないかと思っています。 withで、まとめられなくても、順番を入れ替えたらまとまるものとか、逆にまとめようが無いものとか教えて頂けたらと思います。 よろしくお願いします。 With Selection .Phonetics.Visible = False 'フリガナ表示をオフに .VerticalAlignment = xlCenter .WrapText = False .Orientation = 0 .AddIndent = False .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With With Selection .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(NOT(ISBLANK($A3)),ISBLANK($L3))" .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority End With With Selection.FormatConditions(1).Interior .Pattern = xlSolid .PatternColorIndex = 0 .Color = 65535 .TintAndShade = 0 .PatternTintAndShade = 0 End With With Selection .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(NOT(ISBLANK($A3)),NOT(ISBLANK($D3)))" .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority End With With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .TintAndShade = 0 .PatternTintAndShade = 0 .Color = 5296274 End With With Selection .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(NOT(ISBLANK($A3)),ISBLANK($R3))" .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority End With With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent5 .TintAndShade = 0 End With Selection.FormatConditions(1).StopIfTrue = False

  • Excelマクロの記述をもっとわかりやすくしたいのですが、どなたかご教

    Excelマクロの記述をもっとわかりやすくしたいのですが、どなたかご教示お願いします。 Excel2007使用。下記はマクロを記録として作成しました。省略できるものは省略して見やすくしたいのですが、どこを修正していいのか困っています。 範囲は「A2:A1000、B2:B1000」としていますが、「値が入っている範囲」としたい場合はどのように記述したらよいのでしょうか。 マクロ現在勉強中です。よろしくお願いいたします。 Sub CHK() Range("A2:A1000").Select Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=COUNTIF($B$2:$B$1000,A2)>0" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent2 .TintAndShade = 0.599963377788629 End With Selection.FormatConditions(1).StopIfTrue = False Range("B2:B1000").Select Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _ "=COUNTIF($A$2:$A$1000,B2)>0" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent2 .TintAndShade = 0.599963377788629 End With Selection.FormatConditions(1).StopIfTrue = False End Sub

  • 単一セルではなく範囲に対して条件付き書式を設定するとき

    条件付き書式について質問です。 A7:M15の範囲を「色範囲」と名前定義しているとして、 その範囲の中で「あ」から始まる文字列の場合、 フォントの色を赤色に設定したいのですが、 1つ1つのセルに対して条件付き書式を設定していくのであれば当然出来きるのはわかります。 Workbooks(book1).Sheets(sheet1).Cells("A7").FormatConditions.Add Type:=xlExpression, Formula1:= _ "=COUNTIF(A7,""あ*"")" .FormatConditions(1).interior.colorIndex = 6 Workbooks(book1).Sheets(sheet1).Cells("A8").FormatConditions.Add Type:=xlExpression, Formula1:= _ "=COUNTIF(A8,""あ*"")" .FormatConditions(1).interior.colorIndex = 6 ・・・ ・・・ ・・・ しかし、 範囲全てに対して下記の設定をしてVBAを起動 Workbooks(book1).Sheets(sheet1).Cells(色範囲).FormatConditions.Add Type:=xlExpression, Formula1:= _ "=COUNTIF(A7,""あ*"")" .FormatConditions(1).interior.colorIndex = 6 エクセル側でA8のセルの条件付き書式をみると、 =COUNTIF(A8,"あ*") と自動で行(列)が変わっているのかわかりません。 要は名前定義をした範囲選択、行番号選択、列番号選択どの場合でも、 左上に表示されたセル座標をCOUNTIFの文字列の引数に設定すればいいのでしょうか。 よろしくお願いいたします。

  • 列をアルファベットではなく数値で指定するには

    Vbaで条件付き書式を付ける場合、 列をアルファベットではなく数値で指定するにはどうすればいいですか? Sub Macro() Dim i As Long i = 1 Columns(i).Select Selection.FormatConditions.Delete Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=A1=""aaa""" Selection.FormatConditions(1).Font.ColorIndex = 3 '文字色を赤にする End Sub この場合の、 Formula1:="=A1=""aaa"""のA1を Cells(1,i)みたいにしたいのですが、やり方を教えてください。

  • エクセルVBAで、ある範囲のデータのある行に対して一行おきに色を付けたい

    B3:E3以下の行で一行おきに、C列に文字でも数字でも入力がある場合 その行全体(B:E)を色づけしていきたいのですが、どうすればいいでし ょうか。一般機能の条件付書式でのマクロ記録をとってみましたが、 知識が乏しくどうしたらいいか分かりませんでした。 教えてください。よろしくお願いします。 Sub Macro1() Selection.FormatConditions.Delete Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$C$3<>""""" Selection.FormatConditions(1).Interior.ColorIndex = 3 End Sub

  • エクセルについてです。マウスで選択した範囲に、条件付き書式設定で80点

    エクセルについてです。マウスで選択した範囲に、条件付き書式設定で80点以上のセルの背景を赤にする、というマクロを作成したいと思います。選択する範囲は毎回異なります。以下のマクロはマクロの記録で作成したものです。このRangeの部分をマウスで選択した範囲に変更したいのですが、どうしたら良いのでしょうか?範囲の取得はマクロを実行して、途中で「マウスで範囲を指定してください」というメッセージを表示させてからにしたいのですが。 Sub 背景を赤() Range("B13:E19").Select Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="=80" Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With Selection.FormatConditions(1).Font .Color = -16383844 .TintAndShade = 0 End With With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .Color = 13551615 .TintAndShade = 0 End With End Sub

  • 条件付書式をVBAでセルに設定するときのルール

    図のような列があります。 C列にこだわっているわけではないのですが、その左側にある列で計算をしているという意味で、A、B列はあけただけです。 で、IF文で計算してある条件に合致するとC列で「TRUE」を表示し、合致していない場合はそのときの計算結果を表示させています(IF文的に正しくないので、計算したままの値が計算結果として表示される)。 この結果の見せ方として、これまではC列に「条件付書式」を手動で設定し、文字がTRUEのとき字を青くする表示にしていたのですが、同様の処理を行うExcel Bookファイルが多いため、VBAで条件書式を設定しようとし、次のような記述を実行しました。 すると、図のような結果になりました。 ---------------------------------------------- Sub TestSample() Dim i As Long i = 20 '実際には最終行はBookによって異なるので、 ’行末検索させせていますが、とりあえずここでは20としておきます。 With ActiveSheet Range(Cells(2, 3), Cells(i, 3)).Select With Selection     FormatConditions.Add Type:=xlTextString, String:="TRUE", _     TextOperator:=xlContains     .FormatConditions(1).Font.Color = RGB(0, 50, 255) ’ーーA     .FormatConditions(1).Interior.TintAndShade = 0   ’ーーB End With End With End Sub ---------------------------------------------- 質問が2つあります。 1. 背景がいわゆる「色なし」ではなく白くなっていますが、背景「色なし」かつ「罫線でかこむ」には、どのような記述をすればよいでしょうか 2. FormatConditions.Add Type:~~~~ につづく別の行(Aのところ)に「FormatConditions.」と記述すると実行できません。 マクロで条件書式の自動記録をやって参考にしたところ、添値のような(1)が記録されることに気が付き、それを真似して FormatConditions(1). としたところ、動作しました。 最初だけFormatConditionsで、なぜAのところはFormatConditions(1).となるのか、またAとBはどちらも「FormatConditions(1).」でダブっているのに処理上エラーを返さないのか、理屈がわかりません。 (1)がつく意味と、AとBはどちらも(1)で(ダブっても)動作するのか(逆にいえば、なぜ最初のFormatConditionsだけ、番号がついていないのか、たぶんデフォルトで(0)の意味?) について、このへんの仕組みの解説をよろしくお願いします。

専門家に質問してみよう