A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Nick,
blnResult = False is not really needed because blnResult is always false until it is set True, but here used for completeness.
Youre basefield is Sales and the pivotfield made by youre code has the caption "Sum of Sales".
Then every time 'Set pf = pt.PivotFields("Sales")' makes a new Pivotfield and that is still Hidden, so pf.Orientation is zero (xlHidden).
(and Hans said it already: pf.Orientation = xlDataField = True has to be pf.Orientation = xlDataField for testing pf.Orientation or (pf.Orientation = xlDataField) = True ).
Perhaps this is the better way to test if a pivotfield is present, you don't need to change the default name:
Sub Import()
Dim ws As Worksheet, pvtCache As PivotCache
Dim wsp As Worksheet
Dim pf As PivotField, pt As PivotTable
Dim strName As String
strName = "Sales"
Set wsp = Sheets("Pivot")
Set pt = wsp.PivotTables("PivotTable")
ActiveWorkbook.RefreshAll
Sheets("TP_Coois").Cells.Replace ",", "", xlPart
If Not FieldExists(pt, strName) Then
Set pf = pt.PivotFields(strName)
With pf
.Orientation = xlDataField
.Function = xlSum
End With
pt.PivotCache.Refresh
End If
End Sub
Function FieldExists(pt As PivotTable, strName As String) As Boolean
Dim fld As PivotField
Dim blnResult As Boolean
blnResult = False
For Each fld In pt.VisibleFields
If fld.SourceName = strName Then
blnResult = True
Exit For
End If
Next
FieldExists = blnResult
End Function
Jan