0

我需要根据特定规则对 Excel 2010 中的一些工作表进行排序。例如,在宏运行的工作簿(Workbook_0)中,我有一个单词列表,全部在一行中,每列一个

  • A:“芒果” B:“苹果” C:“香蕉”。我将此范围保存在 Range 类型的变量中。

我的宏创建了一个新的工作簿 (Workbook_1),其中的工作表名为,例如,

  • “apple_count”、“apple_avg”、“banana_count”、“banana_average”、“mango_count”、“mango_avg”。

我想做的是根据 Workbook_0 中指定的顺序对 Workbook_1 中的工作表进行排序。在示例中,我将获得

  • “mango_count”、“mango_avg”、“apple_count”、“apple_avg”、“banana_count”、“banana_avg”。

为了让生活更轻松,我确信 Workbook_1 将只有名称包含在 Workbook_0 中的工作表。尽管问我为什么在创建 Workbook_1 时不对工作表进行排序可能是公平的,但这不是我需要做的。我不确定如何在不产生低效且难以调试的代码的情况下进行此操作。

任何帮助是极大的赞赏!谢谢!

更新:@MattCrum 解决方案效果很好。这是我的最终代码,其中包括一些修改(忽略大小写、修复错误、输出到不同的工作簿、移动其他工作表):

Dim rngTemp As Range, rngAll as Range
Dim shtTemp As Worksheet, shtFound As Worksheet

Set rngAll = Range("A1:A3")
Set shtFound = Sheets(1)

' Sort _count sheets
For Each rngTemp In rngAll
    For Each shtTemp In Workbooks(OutputFileName).Worksheets
        If LCase(shtTemp.Name) = LCase(rngTemp.Value) & "_count" Then
            shtTemp.Move , shtFound
            Set shtFound = shtTemp
        End If
    Next
Next

' Move _avg sheets to the right of correctly ordered _count sheets
For Each rngTemp In rngAll
    For Each shtTemp In Workbooks(OutputFileName).Worksheets
        If LCase(shtTemp.Name) = LCase(rngTemp.Value) & "_time" Then
            shtTemp.Move , Sheets(LCase(rngTemp.Value) & "_count")
        End If
        If LCase(shtTemp.Name) = LCase(rngTemp.Value) & "_avg" Then
            shtTemp.Move , Sheets(LCase(rngTemp.Value) & "_time")
        End If
    Next
Next
4

1 回答 1

0

这是一个相当简单的方法 - 如果你有很多床单,不确定它会有多快,但试一试:

Sub SortSheets()

Dim rngAll As Range, rngTemp As Range
Dim shtTemp As Worksheet, shtFound As Worksheet

Set rngAll = Sheet1.Range("A1:A3")
Set shtFound = Sheets(1)

'Sort _count sheets

    For Each rngTemp In rngAll
        For Each shtTemp In ThisWorkbook.Worksheets
            If shtTemp.Name = rngTemp.Value & "_count" Then
                shtTemp.Move , shtFound
                Set shtFound = shtTemp
            End If
        Next
    Next

'Move _avg sheets to the right of correctly ordered _count sheets

    For Each rngTemp In rngAll
        For Each shtTemp In ThisWorkbook.Worksheets
            If shtTemp.Name = rngTemp.Value & "_avg" Then
                shtTemp.Move , Sheets(rngTemp & "_count")
            End If
        Next
    Next

End Sub
于 2013-01-31T23:13:23.570 回答