Welcome to new things

[Technical] [Electronic work] [Gadget] [Game] memo writing

Sort Excel worksheets by name

I had the opportunity to work with Excel, which has hundreds of worksheets, and I tried to sort the worksheets by name because it was difficult to find the desired sheet.

But Excel doesn't have the ability to sort worksheets by name.

I ended up using VBA (Visual Basic for Applications) to reorder them, so I will note the procedure.

By the way, to select a worksheet from the list of names, right-click on the left arrow at the bottom of Excel to bring up the "Select Sheet" dialog box.

procedure

VBA

Sub excel_sheet_sort()

  Dim path As String
  Dim wb As Object
  Dim ws As Object
  Dim arr As Object
  Dim i As Integer

  ' open excel file
  path = Application.GetOpenFilename("Excel File,*.xls?")
  Set wb = Workbooks.Open(path)

  ' setup sheet name array
  Set arr = CreateObject("System.Collections.ArrayList")

  For Each ws In wb.Worksheets
    arr.Add (ws.Name)
  Next

  ' sort sheet name array
  arr.Sort
  'arr.Reverse

  ' sort sheet
  For i = 1 To (arr.Count - 1)
    wb.Worksheets(arr(i)).Move after:=wb.Worksheets(arr(i - 1))
  Next i

End Sub

Once executed, a file selection dialog will open and you can select the Excel file in which you wish to reorder the worksheets.

It will then open that Excel and reorder the worksheets.

If you want to use descending order, remove the 'arr.Reverse comment.

Other Comments, etc.

If you have an Office 365 business account and can use Office Script, you can also run the following Office Script while Excel is online.

Office Script

function main(workbook: ExcelScript.Workbook) {
  workbook.getWorksheets()
  .map(v=>{
    return {
      obj: v,
      name: v.getName(),
    };
  })
  .sort((a, b)=>{
    if(a.name < b.name) return -1;
    if (a.name > b.name) return 1;
    return 0;
  })
  .forEach((v,i)=>{
    v.obj.setPosition(i);
  });
}

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com