在特定工作表之间排序选择工作表

时间:2013-02-26 17:49:34

标签: excel vba excel-vba

我有一个包含四个“系统”表的工作簿,每个系统表都有一个动态数字或后续标签,用于各种数据收集。我需要的是一种按字母顺序对系统及其子表单进行排序但存在于两个特定表单之间的方法。示例:

  

[简介/参考表] [客户信息表] [系统1] [Sys1儿童1-12] [系统2] [Sys2儿童1-12] [系统3] [Sys3儿童1-12] [系统4] [Sys4 1-12] [其他表]

我尝试过对

等子类进行排序
For Each w1 In Sheets
 For Each w2 In Sheets
  If w1.Range("Z1") <> "" And w2.Range("Z1") <> "" Then
   If w2.Range("Z1").Value < w1.Range("Z1").Value Then
    If w2.Range("Z1").Value = "S1L0" Then
     w2.Move after:=Cover
    Else
     w2.Move before:=w1
    End If
   End If
  End If
 Next w2
Next w1

它开始工作得很好,但是循环失控了,我在目标范围内有一张带有“S1L0”的表,它应该是,而其他一切都在列表的末尾。关于如何让它发挥作用的任何想法?

编辑: 系统表全部以“S1”开头到“S4”,但是它们被重命名为“S1 - %string%”到“S4 - %string%”,子表是最初命名为“S#”的隐藏表的副本L#“其中#分别是系统和子号。子页面也可以重命名,但它将遵循“S#L# - %string%”

模式

1 个答案:

答案 0 :(得分:3)

这应该做的工作:

Sub SortSheets()
    Dim lngParentID As Long, lngChildID As Long
    Dim wsParent As Worksheet, wsChild As Worksheet, wsLast As Worksheet

    Set wsLast = Sheets("Customer Info Sheet")
    For lngParentID = 1 To 4
        Set wsParent = GetSheet(lngParentID)
        If Not wsParent Is Nothing Then
            wsParent.Move After:=wsLast
            Set wsLast = wsParent

            For lngChildID = 1 To 12
                Set wsChild = GetSheet(lngParentID, lngChildID)
                If Not wsChild Is Nothing Then
                    wsChild.Move After:=wsLast
                    Set wsLast = wsChild
                End If
            Next lngChildID
        End If
    Next lngParentID
End Sub

Private Function GetSheet(lngParentID As Long, Optional lngChildID As Long = 0) As Worksheet
    Dim ws As Worksheet

    For Each ws In Sheets
        If (lngChildID = 0 And (ws.Name = "S" & lngParentID Or Left(ws.Name, 4) = "S" & lngParentID & " -")) Or _
            Left(ws.Name, 5) = "S" & lngParentID & "L" & Format(lngChildID, "00") Then
            Set GetSheet = ws
            Exit Function
        End If
    Next
End Function