{"id":68473,"date":"2005-11-22T20:59:00","date_gmt":"2005-11-22T20:59:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2005\/11\/22\/how-can-i-sort-worksheets-in-a-workbook\/"},"modified":"2005-11-22T20:59:00","modified_gmt":"2005-11-22T20:59:00","slug":"how-can-i-sort-worksheets-in-a-workbook","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-sort-worksheets-in-a-workbook\/","title":{"rendered":"How Can I Sort Worksheets in a Workbook?"},"content":{"rendered":"<p><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\"> \n<P>Hey, Scripting Guy! How can I sort worksheets in a workbook?<BR><BR>&#8212; FS<\/P><IMG border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\"><IMG class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\"><A href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><IMG class=\"farGraphic\" title=\"Script Center\" border=\"0\" alt=\"Script Center\" align=\"right\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" height=\"288\"><\/A> \n<P>Hey, FS. How can you sort worksheets in a workbook? Well, to tell you the truth, not as easily as we had <I>hoped<\/I> you could sort worksheets in a workbook. This doesn\u2019t mean it can\u2019t be done; it just means that the process is a tiny bit convoluted. Because of that, don\u2019t feel bad if you don\u2019t fully understand everything we\u2019re about to say; we\u2019re not even sure if <I>we<\/I> fully understand it. But the script seems to work, and, ultimately, that\u2019s all we care about anyway.<\/P>\n<P>Let\u2019s assume we have a workbook that has the following set of worksheets:<\/P><IMG border=\"0\" alt=\"Microsoft Excel\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/excelsort.jpg\" width=\"348\" height=\"129\"> \n<P><BR>How do we sort these worksheets in alphabetical order? Here\u2019s how:<\/P><PRE class=\"codeSample\">On Error Resume Next<\/p>\n<p>Dim arrNames()\nintSize = 0<\/p>\n<p>Set objExcel = CreateObject(&#8220;Excel.Application&#8221;)\nobjExcel.Visible = True<\/p>\n<p>Set objWorkbook = objExcel.Workbooks.Open(&#8220;C:\\Scripts\\Inventory.xls&#8221;)<\/p>\n<p>For Each objWorksheet in objWorkbook.Sheets\n    ReDim Preserve arrNames(intSize)\n    arrNames(intSize) = objWorksheet.Name\n    intSize = intSize + 1\nNext<\/p>\n<p>For i = (UBound(arrNames) &#8211; 1) to 0 Step -1\n    For j= 0 to i\n        If UCase(arrNames(j)) &gt; UCase(arrNames(j+1)) Then\n            strHolder = arrNames(j+1)\n            arrNames(j+1) = arrNames(j)\n            arrNames(j) = strHolder\n        End If\n    Next\nNext <\/p>\n<p>For i = UBound(arrNames) to 1 Step -1\n    Set objSheet1 = objWorkbook.Sheets(arrNames(i))\n    Set objSheet2 = objWorkbook.Sheets(arrNames(i-1))\n    objSheet2.Move objSheet1\nNext\n<\/PRE>\n<P>Yes, yes, we know. But we\u2019re going to try to explain this as best we can.<\/P>\n<P>Actually the script starts off simply enough. We begin by creating a dynamic array named arrNames(). Why? Well, although Excel has a ton of features built into it, it is missing at least one thing: a command for sorting worksheets. Because Excel has no built-in method for sorting worksheets we\u2019re going to have to take care of that ourselves. And the way we\u2019re going to do that is by grabbing all the worksheet names, storing those names in a dynamic array, and then sorting the items in that array. Once we\u2019ve sorted the array we\u2019ll know the correct order for all the worksheets; at that point we can then use Excel\u2019s <B>Move<\/B> method to move each worksheet to the desired location.<\/P>\n<P>So after we create the array we have some standard boilerplate code that creates an instance of the <B>Excel.Application<\/B> object, sets the <B>Visible<\/B> property to True, and then uses the <B>Open<\/B> method to open the file C:\\Scripts\\Inventory.xls. Now we\u2019re ready to roll up our sleeves and start working.<\/P>\n<P>The first thing we need to do is grab all the worksheet names and put them into our dynamic array. That\u2019s what we do in this block of code:<\/P><PRE class=\"codeSample\">For Each objWorksheet in objWorkbook.Sheets\n    ReDim Preserve arrNames(intSize)\n    arrNames(intSize) = objWorksheet.Name\n    intSize = intSize + 1\nNext\n<\/PRE>\n<P>All we\u2019re doing here is setting up a For Each loop to loop through the <B>Sheets<\/B> collection; as the name implies, this collection consists of all the worksheets found in our workbook. For each worksheet in the collection we use the <B>ReDim Preserve<\/B> command to resize our dynamic array. The array starts off as size 0, meaning it\u2019s an array with a single item. (An array size will always be the number of items in the array minus 1.) How do we know that we set the size to 0? Because we assigned it the value of a counter variable named intSize, a variable that we set to 0 at the beginning of the script.<\/P>\n<P>We then assign the first item in the array the name of the first worksheet in the collection; that\u2019s what we do here:<\/P><PRE class=\"codeSample\">arrNames(intSize) = objWorksheet.Name\n<\/PRE>\n<P>We increment our counter variable by 1, then loop around and repeat the process for the second worksheet in the collection, a worksheet whose name will become the second item in our array. When we\u2019re all done we\u2019ll have an array consisting of the following items, in this order:<\/P><PRE class=\"codeSample\">Sheet2\nc\na\nSheet1\nb\n<\/PRE>\n<P>OK, that wasn\u2019t <I>too<\/I> bad. That\u2019s not necessarily true of this next section, however. Here we use a \u201csimple\u201d bubble sort to sort the items in the array in alphabetical order:<\/P><PRE class=\"codeSample\">For i = (UBound(arrNames) &#8211; 1) to 0 Step -1\n    For j= 0 to i\n        If UCase(arrNames(j)) &gt; UCase(arrNames(j+1)) Then\n            strHolder = arrNames(j+1)\n            arrNames(j+1) = arrNames(j)\n            arrNames(j) = strHolder\n        End If\n    Next\nNext\n<\/PRE>\n<P>We\u2019re not going to try and explain the ins and outs of a bubble sort in today\u2019s column; for a reasonably good explanation of how this works you might take a look at the Scripting Week 2 webcast <A href=\"http:\/\/msevents.microsoft.com\/cui\/eventdetail.aspx?EventID=1032268755&amp;culture=en-US\" target=\"_blank\"><B>Things the Scripting Guys Never Told You<\/B><\/A>. In short, what happens in a bubble sort is that you compare each item in the array with every other item in the array, and then swap their places in that array if need be. For example, our first two items in the array are these:<\/P><PRE class=\"codeSample\">Sheet2\nc\n<\/PRE>\n<P>Alphabetically-speaking, c comes before Sheet2. Therefore, our bubble sort will swap those two names, meaning that <I>these<\/I> become the first two items in the array:<\/P><PRE class=\"codeSample\">c\nSheet2\n<\/PRE>\n<P>This continues until each item has been compared with every other item. The net result? An array sorted in alphabetical order:<\/P><PRE class=\"codeSample\">a\nb\nc\nSheet1\nSheet2\n<\/PRE>\n<P>As luck would have it, this also turns out to be the order we want for our spreadsheets. Now that we know which spreadsheet should come first, which should come second, etc., we can use this block of code to rearrange the spreadsheets within the workbook:<\/P><PRE class=\"codeSample\">For i = UBound(arrNames) to 1 Step -1\n    Set objSheet1 = objWorkbook.Sheets(arrNames(i))\n    Set objSheet2 = objWorkbook.Sheets(arrNames(i-1))\n    objSheet2.Move objSheet1\nNext\n<\/PRE>\n<P>What we\u2019re doing here is starting at the end of the array (<B>UBound<\/B> connects us to the last item in the array, in this case Sheet2) and then working our way down (that\u2019s what the <B>Step -1<\/B> does). Thanks to our sorted array we know that the last item in the array &#8211; Sheet2 &#8211; should also be the last worksheet in the workbook. We also know that the next-to-last item in the array &#8211; Sheet1 &#8211; should be the next-to-last worksheet in the workbook. Therefore, we use this code to create an object reference to Sheet 2:<\/P><PRE class=\"codeSample\">Set objSheet1 = objWorkbook.Sheets(arrNames(i))\n<\/PRE>\n<P>We then use this code to create an object reference to Sheet1:<\/P><PRE class=\"codeSample\">Set objSheet2 = objWorkbook.Sheets(arrNames(i-1))\n<\/PRE>\n<P>Finally, we call the <B>Move<\/B> method to move Sheet1 in front of (before) Sheet2:<\/P><PRE class=\"codeSample\">objSheet2.Move objSheet1\n<\/PRE>\n<P>How did we know that Sheet1 would be moved in front of Sheet2? That\u2019s easy: there\u2019s no comma after the Move method:<\/P><PRE class=\"codeSample\">objSheet2.Move objSheet1\n<\/PRE>\n<P>If we wanted to move Sheet1 in back of (after) Sheet2 then we <I>would<\/I> put a comma after the Move method:<\/P><PRE class=\"codeSample\">objSheet2.Move, objSheet1\n<\/PRE>\n<P>Admittedly, this isn\u2019t the most intuitive thing in the world, but it works.<\/P>\n<P>When all is said and done, we\u2019ll end up with a workbook that looks like this:<\/P><IMG border=\"0\" alt=\"Microsoft Excel\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/qanda\/excelsort1.jpg\" width=\"348\" height=\"129\"> \n<P><BR>And if you aren\u2019t totally sure how we got to that point, well, don\u2019t worry about it. Sometimes it\u2019s enough just to have faith, without questioning the how or the why.<\/P><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I sort worksheets in a workbook?&#8212; FS Hey, FS. How can you sort worksheets in a workbook? Well, to tell you the truth, not as easily as we had hoped you could sort worksheets in a workbook. This doesn\u2019t mean it can\u2019t be done; it just means that the process [&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-68473","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! How can I sort worksheets in a workbook?&#8212; FS Hey, FS. How can you sort worksheets in a workbook? Well, to tell you the truth, not as easily as we had hoped you could sort worksheets in a workbook. This doesn\u2019t mean it can\u2019t be done; it just means that the process [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/68473","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=68473"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/68473\/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=68473"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=68473"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=68473"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}