如果有人感兴趣,我终于找到了一个可以接受的解决方案。它使用数据透视表和TextToColumns函数的组合。一旦我有了这个方法,把它变成代码就很简单了。下面的代码确实引用了我使用的一些便利功能,例如“DeleteSheet”和“LastRowOn”,但您明白了。
Sub Foo()
Dim ws As Worksheet
For Each ws In Worksheets
If IsStaffingSheet(ws) Then
ws.Select
DeleteSheet ws.Name & " - Exploded"
TransposeSheet ws
End If
Next ws
End Sub
Sub TransposeSheet(ByVal ParentSheet As Worksheet)
Dim ws As Worksheet
Dim r As Range
Dim ref As Variant
Dim pt As PivotTable
Set r = Range("StaffingStartCell")
Set r = Range(r, r.SpecialCells(xlLastCell))
ref = Array("'" & ActiveSheet.Name _
& "'!" & r.Address(ReferenceStyle:=xlR1C1))
Application.CutCopyMode = False
ActiveWorkbook.PivotCaches.Add(SourceType:=xlConsolidation, _
SourceData:=ref).CreatePivotTable TableDestination:="", _
tableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion10
Set ws = ActiveSheet
Set pt = ws.PivotTableWizard(TableDestination:=ActiveSheet.Cells(3, 1))
pt.DataPivotField.PivotItems("Count of Value").Position = 1
pt.PivotFields("Row").PivotItems("").Visible = False
ExplodePivot ParentSheet
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
Set ws = Nothing
End Sub
Sub ExplodePivot(ByVal ParentSheet As Worksheet)
Dim lastRow As Long
Dim lastCol As Long
lastRow = LastRowOn(ActiveSheet.Name)
lastCol = LastColumnBack(ActiveSheet, lastRow)
Cells(lastRow, lastCol).ShowDetail = True
Columns("B:C").Select
Selection.Cut Destination:=Columns("S:T")
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("A1"), _
DataType:=xlDelimited, _
Semicolon:=True
Selection.ColumnWidth = 12
ActiveSheet.Name = ParentSheet.Name & " - Exploded"
End Sub