|
VBA实现的,看看能不能符合你的需求:
- Sub SwapAllRowColumnFields()
- Dim ws As Worksheet
- Dim pt As PivotTable
- Dim pf As PivotField
- Dim rowFieldsList As New Collection
- Dim colFieldsList As New Collection
- Dim pivotName As String
- Dim i As Integer
-
- ' 指定要操作的透视表名称
- pivotName = "数据透视表1"
-
- ' 设置工作表和透视表
- On Error Resume Next
- Set ws = ActiveWorkbook.Worksheets("Sheet1") ' 修改为包含透视表的工作表名称
- Set pt = ws.PivotTables(pivotName)
- On Error GoTo 0
-
- If Not pt Is Nothing Then
- ' 收集所有的行字段和列字段
- For Each pf In pt.RowFields
- rowFieldsList.Add pf.Name
- Next pf
-
- For Each pf In pt.ColumnFields
- colFieldsList.Add pf.Name
- Next pf
-
- ' 移除所有行字段和列字段
- For Each pf In pt.RowFields
- pf.Orientation = xlHidden
- Next pf
-
- For Each pf In pt.ColumnFields
- pf.Orientation = xlHidden
- Next pf
-
- ' 将原来的行字段添加到列字段,原来的列字段添加到行字段
- For i = 1 To rowFieldsList.Count
- pt.PivotFields(rowFieldsList(i)).Orientation = xlColumnField
- Next i
-
- For i = 1 To colFieldsList.Count
- pt.PivotFields(colFieldsList(i)).Orientation = xlRowField
- Next i
-
- ' 提示用户完成操作
- MsgBox "透视表 '" & pt.Name & "' 的所有行列字段已成功互换。", vbInformation
- Else
- MsgBox "未找到名称为 '" & pivotName & "' 的透视表。", vbCritical
- End If
- End Sub
复制代码
|
|