{"id":56323,"date":"2008-01-29T22:28:00","date_gmt":"2008-01-29T22:28:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2008\/01\/29\/hey-scripting-guy-how-can-i-change-the-color-of-a-spreadsheet-cell-based-on-a-range-of-values\/"},"modified":"2008-01-29T22:28:00","modified_gmt":"2008-01-29T22:28:00","slug":"hey-scripting-guy-how-can-i-change-the-color-of-a-spreadsheet-cell-based-on-a-range-of-values","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/hey-scripting-guy-how-can-i-change-the-color-of-a-spreadsheet-cell-based-on-a-range-of-values\/","title":{"rendered":"Hey, Scripting Guy! How Can I Change the Color of a Spreadsheet Cell Based on a Range of Values?"},"content":{"rendered":"<p><img decoding=\"async\" height=\"34\" width=\"34\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" align=\"left\" alt=\"Hey, Scripting Guy! Question\" border=\"0\" title=\"Hey, Scripting Guy! Question\" class=\"nearGraphic\" \/><\/p>\n<p>Hey, Scripting Guy! I need a script that can read all the values in a spreadsheet and then change the background colors of the cells in that spreadsheet based on a range of values. For example, if the value is less than 20 the cell gets colored one color; if the cell is between 20 and 40 it gets colored another color; and so on. How do I do that?<\/p>\n<p>&#8212; ESW<\/p>\n<p><img decoding=\"async\" height=\"5\" width=\"5\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" alt=\"Spacer\" border=\"0\" \/><img decoding=\"async\" height=\"34\" width=\"34\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" align=\"left\" alt=\"Hey, Scripting Guy! Answer\" border=\"0\" title=\"Hey, Scripting Guy! Answer\" class=\"nearGraphic\" \/><a href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><img decoding=\"async\" height=\"288\" width=\"120\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" align=\"right\" alt=\"Script Center\" border=\"0\" title=\"Script Center\" class=\"farGraphic\" \/><\/a><\/p>\n<p>Hey, ESW. For you weather junkies out there, yes, last night the Seattle area got hit with another mid-winter snow storm, something that must have dumped at least an inch, maybe even an <i>inch and a half<\/i> of snow on the house of the Scripting Guy who writes this column. Could it be the end of the world? Actually, people in this part of the country would have a much better chance of surviving the end of the world than they have of getting through a little bit of snow. (&ldquo;Snow weenies&rdquo; is the term often tossed in our direction. We&rsquo;d take exception to that, but we can&rsquo;t: there&rsquo;s snow on the ground, which means we can&rsquo;t do anything. And that includes taking exception to something.)<\/p>\n<p>Of course, we know what many of you are thinking: &ldquo;Oh my gosh, a whole inch and a half of snow! How will you poor Seattleites survive such a nightmare!?!&rdquo; Well, we can&rsquo;t speak for everyone in the Puget Sound region. However, we <i>can<\/i> tell you that the Scripting Guy who writes this column plans to survive the nightmare by lounging around the house, eating doughnuts, drinking coffee, and watching a lot of TV.<\/p>\n<p>Oh, and, uh &hellip; working &hellip; from home. <\/p>\n<table cellpadding=\"0\" cellspacing=\"0\" class=\"dataTable\" id=\"EFD\">\n<thead><\/thead>\n<tbody>\n<tr valign=\"top\" class=\"record\">\n<td>\n<p><b>Note<\/b>. Does this mean that the Scripting Guy who writes this column is a snow weenie? Maybe. But, then again, he&rsquo;s also sitting at home in pair of sweatpants and a sweatshirt while you non-snow weenies are all dressed up and hard at work.<\/p>\n<p>Think about it.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>To his credit, the Scripting Guy who writes this column originally <i>did<\/i> plan on trying to make it in to work this morning. As he was watching the snow fall, however, he noticed his neighbor attempt to drive up the hill. A moment later, he watched as that same neighbor come backing down the hill. The neighbor tried again; less than a minute later he was backing down into his driveway. After the neighbor&rsquo;s third unsuccessful try at negotiating the hill the Scripting Guy who writes this column said to himself, &ldquo;I think I&rsquo;ll have another doughnut.&rdquo;<\/p>\n<p>And then, after that, he decided to work from home today.<\/p>\n<p>Anyway, right now it&rsquo;s snowing again (although the sound on the rooftop suggests that there might be little sleet mixed in) and the only thing on TV is some 30-year-old game show being shown on the Game Show Network. That means we might as well take a few minutes to see if we can write a script that can change the background color of a cell based on a range of values.<\/p>\n<p>Well, how about that? Turns out that we <i>can<\/i> write just such a script:<\/p>\n<pre class=\"codeSample\">Set objExcel = CreateObject(\"Excel.Application\")\nobjExcel.Visible = True\n\nSet objWorkbook = objExcel.Workbooks.Open(\"C:\\Scripts\\Test.xls\")\nSet objWorksheet = objWorkbook.Worksheets(1)\n\nSet objRange = objWorksheet.UsedRange\n\nFor Each objCell in objRange\n    If IsNumeric(objCell.Value) Then\n       \n        If objCell.Value &lt; 20 Then\n            objCell.Interior.ColorIndex = 3\n        ElseIf objCell.Value &lt; 40 Then\n            objCell.Interior.ColorIndex = 6\n        ElseIf objCell.Value &lt; 60 Then\n            objCell.Interior.ColorIndex = 45\n        End If\n    End If\nNext<\/pre>\n<p>As you can see, this was actually a pretty easy little script to come up with. We start things off by creating an instance of the <b>Excel.Application<\/b> object and set <br \/>the <b>Visible<\/b> property to True; that gives us a running instance of Microsoft Excel that we can see on screen. We then use these two lines of code to open <br \/>the file C:\\Scripts\\Test.xls and bind to the first worksheet in that file:<\/p>\n<pre class=\"codeSample\">Set objWorkbook = objExcel.Workbooks.Open(\"C:\\Scripts\\Test.xls\")\nSet objWorksheet = objWorkbook.Worksheets(1)<\/pre>\n<p>At this point, we&rsquo;re ready to have some <i>real<\/i> fun!<\/p>\n<p>Oh, right: we have to finish today&rsquo;s column first, don&rsquo;t we? OK, let&rsquo;s finish today&rsquo;s column first. <i>Then<\/i> we&rsquo;ll be ready to have some real fun!<\/p>\n<p>Oh, right: the <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/funzone\/games\/default.mspx\"><b>2008 Winter Scripting Games<\/b><\/a> don&rsquo;t start until February 15<sup>th<\/sup>. OK, let&rsquo;s finish today&rsquo;s column, and then sit around until February 15<sup>th<\/sup>. And <br \/><i>then<\/i> we&rsquo;ll be ready to have some real fun!<\/p>\n<p>In the meantime, we use this line of code to create an instance of Excel&rsquo;s <b>Range<\/b> object, a range that encompasses all the cells in the spreadsheet that contain <br \/>data. (Hence the name <i>UsedRange<\/i>.):<\/p>\n<pre class=\"codeSample\">Set objRange = objWorksheet.UsedRange<\/pre>\n<p>Why do we want a collection of all the cells in the spreadsheet that contain data? You got it: that makes it very easy to loop through all the cells and, if the <br \/>value of a cell warrants, change the background color.<\/p>\n<p>To do that, we begin by setting up a For Each loop to loop through all the items in the range (that is, all the cells in the spreadsheet). Inside that loop we use <br \/>the <b>IsNumeric<\/b> function to see if the <b>Value<\/b> of the cell is even a number in the&nbsp;first place. If it is, we then use this block of code to determine the exact value, <br \/>and to see if the value falls in any of our specified ranges:<\/p>\n<pre class=\"codeSample\"><pre class=\"codeSample\">If objCell.Value &lt; 20 Then\n    objCell.Interior.ColorIndex = 3\nElseIf objCell.Value &lt; 40 Then\n    objCell.Interior.ColorIndex = 6\nElseIf objCell.Value &lt; 60 Then\n    objCell.Interior.ColorIndex = 45\nEnd If\n<\/pre>\n<p>As you can see, in line 1 we check to see if the Value of the cell is less than 20. If it is, we then use this line of code to set the background color of the cell to <br \/>red:\n<\/p>\n<pre class=\"codeSample\">objCell.Interior.ColorIndex = 3<\/pre>\n<table cellpadding=\"0\" cellspacing=\"0\" class=\"dataTable\" id=\"EXF\">\n<thead><\/thead>\n<tbody>\n<tr valign=\"top\" class=\"record\">\n<td>\n<p><b>Note<\/b>. How did we know that setting the <b>Interior.ColorIndex<\/b> property to 3 would change the background color of the cell to red? Well, you might say that <br \/>a little birdie told us.<\/p>\n<p>Well, OK; actually, that little birdie told us to read the <i>Office Space<\/i> article <a href=\"http:\/\/www.microsoft.com\/technet\/scriptcenter\/resources\/officetips\/mar05\/tips0329.mspx\"><b>Changing the Background Color of a Cell<\/b><\/a>. Either way, though, the background <br \/>color gets changed to red.<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div class=\"dataTableBottomMargin\"><\/div>\n<p>Suppose that the Value of the cell <i>is<\/i> less than 20. In that case, the background color of the cell gets changed to red, and we automatically exit the If Then <br \/>block; as soon as VBScript encounters a true condition it exits an If Then statement. Now, what if the value <i>isn&rsquo;t<\/i> less than 20? Well, in that case we check <br \/>the next condition: is the Value less than 40? If it is, then we change the background color to yellow (6). If it&rsquo;s not, then we check our final condition: is the Value <br \/>less than 60? If it is, we change the background color to orange (45); if it&rsquo;s not, we leave the cell color as-is. Regardless, we then zip back to the top of the <br \/>loop and repeat the process with the next cell in the spreadsheet.<\/p>\n<p>When all is said and done we should have a spreadsheet that looks like this:<\/p>\n<p><img decoding=\"async\" height=\"304\" width=\"308\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/colorcells.jpg\" alt=\"Spacer\" border=\"0\" \/><\/p>\n<p>Beautiful, yet functional. Just like the Scripting Guys.<\/p>\n<p>That should do it, ESW. As for the Scripting Guy who writes this column, he has a busy day ahead of him. For example, should he make himself a grilled <br \/>cheese sandwich for lunch, or should he walk over to Dairy Queen and get a hamburger? Boy, working at home is proving to be much harder than he thought <br \/>it would be.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! I need a script that can read all the values in a spreadsheet and then change the background colors of the cells in that spreadsheet based on a range of values. For example, if the value is less than 20 the cell gets colored one color; if the cell is between 20 [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[710,48,49,3,5],"class_list":["post-56323","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-excel-spreadsheet","tag-microsoft-excel","tag-office","tag-scripting-guy","tag-vbscript"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! I need a script that can read all the values in a spreadsheet and then change the background colors of the cells in that spreadsheet based on a range of values. For example, if the value is less than 20 the cell gets colored one color; if the cell is between 20 [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/56323","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=56323"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/56323\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=56323"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=56323"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=56323"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}