有趣的問題:)希望我理解正確的查詢:P
比方說,我們有這樣的支點?
所以,如果你想要的結果這樣
AAAA
AAAB
AAAC
AAAD
BBBA
BBBB
BBBC
BBBD
CCCA
CCCB
CCCC
CCCD
DDDA
dddB
DDDC
DDDD
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2
C3
C4
D1
D2
D3
D4
然後你可以使用此代碼。該示例將數據輸出到Col G(在這種情況下)。如果您有超過6個數據透視字段,則必須更改它。
Option Explicit
Sub Sample()
Dim pvtField As PivotField
Dim pvtItem As PivotItem
Dim MyArray() As String
Dim ws As Worksheet, wsTemp As Worksheet
Dim i As Long, j As Long, k As Long, l As Long, m As Long
Dim LastRow As Long, LastCol As Long, LastRowNC As Long
'~~> Set ws to sheet which has the relevant pivot table
Set ws = Sheets("Sheet1")
ws.Activate
'~~> Add a temp sheet for output
Set wsTemp = Sheets.Add
j = 0
'~~> Loop through all pivot fields in the relevant pivot
'~~> Change "PivotTable1" to the relevant pivot table name
For Each pvtField In ws.PivotTables("PivotTable1").PivotFields
i = 1
j = j + 1
For Each pvtItem In pvtField.PivotItems
'~~> Output the Pivot items in a temp sheet
With wsTemp
.Cells(i, j).Value = pvtItem.Value
i = i + 1
End With
Next
Next
'~~> Get the lastrow in the temp sheet
LastRow = wsTemp.Cells.Find(What:="*", After:=wsTemp.[A1], SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
'~~> Get the lastcol in the temp sheet
LastCol = wsTemp.Cells.Find(What:="*", After:=wsTemp.Range("A1"), Lookat:=xlPart, LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column
m = 1: j = 0
'~~> Create the necessary combinations
With wsTemp
For i = 1 To LastCol
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
If .Cells(1, i + 1) <> "" Then
LastRowNC = .Cells(.Rows.Count, i + 1).End(xlUp).Row
For k = 1 To LastRow
For l = 1 To LastRowNC
'~~> Output combinations in Col G
'~~> You will have to change this if you have
'~~> more than 6 pivot fields
.Range("G" & m).Value = .Cells(k, i) & .Cells(l, i + 1)
m = m + 1
Next
Next
End If
Next i
End With
End Sub
希望這是你想要的嗎?如果沒有,那麼讓我知道,我會修改它。
示例工作簿可以從here下載。這個鏈接將會持續7天。
HTH
希德
感謝您的時間,但對不起,不,這不是我所期待的。 A)它應該只結合當前在數據透視表中的字段。 B)您的代碼不會生成所有組合,因爲它似乎將兩個字段(當前和下一個樞軸字段)組合在一起。 C)引用.PivotFields似乎將數據值視爲一個樞軸字段,這並不理想。 – 2012-02-19 17:08:05