【问题标题】:Sorting select sheets between specific sheets在特定工作表之间对选择工作表进行排序
【发布时间】:2013-02-27 04:24:33
【问题描述】:

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

[介绍/参考表] [客户信息表] [系统 1] [Sys1 Child 1-12] [System 2] [Sys2 Child 1-12] [System 3] [Sys3 Child 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%”

【问题讨论】:

  • 如果没有相关数据样本,很难发现问题所在。
  • 您能否详细说明您如何决定哪个工作表是哪个工作表?您似乎查看了“Z1”范围,但您没有提供您实施的具体规则以了解哪个工作表是系统/子表...
  • 对不起,系统表都以“S1”到“S4”开头,但它们被重命名为“S1 - %string%”到“S4 - %string%”,子表是副本最初命名为“S#L#”的隐藏工作表,其中 # 分别是系统编号和子编号。子表也可以重命名,但它将遵循模式“S#L# - %string%”

标签: vba excel


【解决方案1】:

这应该可以完成工作:

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

【讨论】:

  • 它开始很强大,但它通过将所有父工作表与子工作表分开放置而结束。
  • 不确定我是否理解。结果顺序应该是 S1, S1L1, S1L2, S2, S2L1, ... 不是这样吗?
  • 不,它将对 S1 系列进行排序,(S1、S1L1、S1L2 等)然后是 S2s,当 S2 系列排序后,它会将 S2 放在 S1 之后,离开 S2L1、S2L2 等在 S1L1、S1L2 等之后。模式与 S3 和 S4 重复。我只剩下 S1、S2、S3、S4、S1L1、S2L1、S3L1、S4L1
  • 我想知道是不是两位数的孩子ID有问题,如果它
  • 可能就是这样!如果名称包含前导 0,请将 Left(ws.Name, 4) = "S" &amp; lngParentID &amp; "L" &amp; lngChildID 替换为 Left(ws.Name, 5) = "S" &amp; lngParentID &amp; "L" &amp; Format(lngChildID,"00")。否则,请将您的工作簿发给我(查看我的个人资料
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 2011-06-04
相关资源
最近更新 更多