通过宏基于工作表名称重新排序Excel表格

时间:2014-01-15 19:49:32

标签: excel excel-vba excel-2007 excel-2010 vba

如果我的excel文档中有6张名称并按此顺序排列:O1,O2,O3,O1_#2,O2#2,O3#3

是否可以编写宏来更改这些表的顺序? 这是我正在寻找的序列: O1,O1#2,O2,O2#2,O3,O3#2

由于

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您需要按字母顺序对工作表进行排序:

Sub SortSheets()

    Dim shNames As Collection
    Dim i As Long, j As Long
    Dim temp As String
    Dim sh As Worksheet

    Set shNames = New Collection

    'add sheet names in collection
    For Each sh In ThisWorkbook.Worksheets
        shNames.Add sh.Name, sh.Name
    Next sh

    'bubble sort
    For i = 1 To shNames.Count - 1
        For j = i + 1 To shNames.Count
            If shNames(i) > shNames(j) Then
               temp = shNames(j)
               shNames.Remove j
               shNames.Add temp, temp, i
            End If
        Next j
    Next i

   ' move sheets
   For i = shNames.Count - 1 To 1 Step -1
       Worksheets(shNames(i)).Move Before:=Sheets(1)
   Next i

End Sub