sort selected worksheets A-Z by means of a macro

Dear Experts:

I would like to run a macro that performs the following action:

The currently contiguously selected worksheets are to be sorted A-Z.

Help is much appreciated. Thank you very much in advance.

Regards, Andreas
Andreas HermleTeam leaderAsked:
Who is Participating?
Rgonzo1971Connect With a Mentor Commented:

pls try
Sub SortWorksheets()
    Dim N As Integer
    Dim M As Integer
    Set sel = ActiveWindow.SelectedSheets
    For M = 1 To sel.Count
        For N = M To sel.Count
            If UCase(sel.Item(N).Name) < UCase(sel.Item(M).Name) Then
                sel.Item(N).Move Before:=sel.Item(M)
            End If
        Next N
    Next M
End Sub

Open in new window

Roy CoxGroup Finance ManagerCommented:
Try this
Option Explicit

Sub SortWorksheets()

''/// sort worksheets in a workbook in ascending order

    Dim iCnt As Integer, iX As Integer, iJ As Integer

    Application.ScreenUpdating = False

    iCnt = Worksheets.Count

    If iCnt = 1 Then Exit Sub

    For iX = 1 To iCnt - 1

        For iJ = iX + 1 To iCnt

            If Worksheets(iJ).Name < Worksheets(iX).Name Then

                Worksheets(iJ).Move Before:=Worksheets(iX)

            End If

        Next iJ

    Next iX

End Sub

Open in new window

Andreas HermleTeam leaderAuthor Commented:
Hi Roy,

thank you very much for your swift and professional help. As a matter of fact I would sort just the selected ones and leave the non-selected alone.

Is this possible?

Regards, Andreas
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

NorieVBA ExpertCommented:

Are the selected sheets contiguous?
Roy CoxGroup Finance ManagerCommented:
This code here should do that
Andreas HermleTeam leaderAuthor Commented:
Hi Rafael, this did the trick and all my selected sheets (contiguous) got sorted. Thank you very much.

To all the others, thank you very much for your great, professional and swift support.

Regards, Andreas
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.