2016-02-15 1 views
0

создать сводную таблицу:Excel VBA: как добавить новое поле с формулой в сводную таблицу?

ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=Sheets("Working").UsedRange).CreatePivotTable TableDestination:="", TableName:="HDPivotTable", DefaultVersion:=xlPivotTableVersion10 
ActiveSheet.Name = "HD Pivot" 

ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(1, 1) 

ActiveSheet.PivotTables("HDPivotTable").AddFields RowFields:="Location Code" 

ActiveSheet.PivotTables("HDPivotTable").PivotFields("h,d,x").Orientation = xlDataField 


With ActiveSheet.PivotTables("HDPivotTable").PivotFields("h,d,x") 
    .Orientation = xlColumnField 

    For i = 1 To .PivotItems.Count 
     ' Filter out columns that are not "D" or "H" 
     If .PivotItems(i) <> "D" And .PivotItems(i) <> "H" Then 
      .PivotItems(i).Visible = False 
     End If 
    Next  

End With 

Так результирующая таблица выглядит следующим образом:

enter image description here

Мне нужно добавить новый столбец «T/F» после Великого Всего, что было бы TRUE, если значения в столбцах «D» и «H» равны, а FALSE в противном случае. У меня он красный и подсвеченный. Я не могу заставить его работать, что бы я ни пытался. Я не эксперт в VBA или Excel, поэтому я мог бы попробовать все, что нашел в Интернете. Не могли бы вы помочь?

Спасибо.

+0

Вы только хотите/нужно добавить FIEL к стержень ?? Или вы можете поместить формулу рядом с точкой поворота? Если вам не нужны форматы, это может быть сделано без боли. –

+0

@ ElbertVillarreal. Он не должен находиться в точке опоры, но сам лист добавляется, когда создается свод (свод создан в новой рабочей таблице). –

+0

Пожалуйста, проверьте изменения №3 в ответе –

ответ

0

Это вернет 1, если TRUE или 0 если есть FALSE.

ActiveSheet.PivotTables("HDPivotTable").CalculatedFields.Add "Compare", "=Monto ='D/Monto'", True 
    'Where: 
    'Compare : Is the name of the field (you use "T/F") 
    '"=Monto = 'D/Monto'" : Is the comparison of fields you want in your case would be 
    '"=D = H" <== that way 
ActiveSheet.PivotTables("HDPivotTable").PivotFields("Compare").Orientation = xlDataField 
    'Here you add the field to the pivot 

Edit # 1 ПримечаниеЭтот: В первой строке добавить поле, и так как не может быть два поля с одинаковым именем, если вы запустите макрос дважды, вы получите сообщение об ошибке в первая строка.

Если вы уже создали поле («Сравнить», используя мой пример), вам нужно только добавить fiel к xlDataField.

Edit 2

Просто решили изменить эти вопросы ...

Sub addComp() 

    Dim r 'to store the last row 
    Dim c 'to store the last column 

    c = Application.WorksheetFunction.Match("Grand Total", Range("A3").EntireRow, 0) 
     'to find the last column of the pivot 
     'in your case would be "Grand Total" 
     'if add 1 to c, we get the column next to the pivot 
     ' 
     'In my example, I use my own header, but you can use yours. 
     'In your question you use "Grand total", i change it. 
     ' 
     'And that is why you get and error, becuase MATCH was looking for "Sum of D/Monto", 
     'not "Grand total" 
    r = Range(Cells(3, c), Cells(3, c)).End(xlDown).Row 
     'here I use the 3th row because, in my case my pivot is in the 
     '3th row, but you can use the row you want/need 
     'that range/row, is the reference that use the pivot to set its position 
     'inside the worksheet. 
     'And using that row as a reference, whith the code 
     'r = Range(Cells(3, c), Cells(3, c)).End(xlDown).Row I just find the last row down 
     'no matter how many rows be. Is like, to manually got to the "Grand total" header, 
     'press Shift+DownArrow, and you will go to the last row, the code above do the very same. 
     ' 
     'To find the las row of the pivot 

    Range(Cells(3, c + 1), Cells(3, c + 1)).Value = "T/F" 
     'Here adds the name of our field 
    Range(Cells(4, c + 1), Cells(r - 1, c + 1)).FormulaR1C1 = "=RC[-2]=RC[-1]" 
     'Here add the TRUE/FALSE to all the cells in the next column of the pivot. 
     'I don't use the formula with the Grand total row, but if you want, 
     'just remove the " - 1" next to r in the second Cells 
End Sub 

Edit # 3

Sub addComp() 
    Dim r 'to store the last row 
    Dim c 'to store the last column 
    c = Application.WorksheetFunction.Match("Grand Total", Range("A2").EntireRow, 0) 
    r = Range(Cells(2, c), Cells(2, c)).End(xlDown).Row 
    Range(Cells(2, c + 1), Cells(2, c + 1)).Value = "T/F" 
    Range(Cells(3, c + 1), Cells(r - 1, c + 1)).FormulaR1C1 = "=RC[-2]=RC[-1]" 
End Sub 
+0

Спасибо Elbert. Я попробовал это и получил ошибку во второй строке: Ошибка времени выполнения «1004»: не удалось получить свойство PivotFields класса PivotTable. –

+0

У вас есть ошибка, возможно, потому что вы не изменяете имя поля «Сравнить» с именем, которое вы используете. В вашем вопросе вы используете «T/F». Используйте правильное имя и скажите мне, нужно ли вам некоторое улучшение. –

+0

Я изменил его ... –

Смежные вопросы