2017-10-11 83 views
-1

我似乎被困在什麼應該是一個基本問題。我正在嘗試將所有過濾器與VBA一起編碼。我對這種語言很陌生,我認爲我完全從Lynda.com上的一個文件中複製了這些內容,但我被卡住了。任何幫助都會很棒。當我嘗試運行一個宏時,我得到了一個錯誤。下一個沒有適用於VBA Excel

Dim pt As PivotTable 
    Application.ScreenUpdating = False 
    For Each pt In Active.Sheet.PivotTables 
    With pt.PivotFields("Parent Company") 
     .Orientation = xlPageField 
     .Position = 1 
    End With 
    With pt.PivotFields("Milestone") 
     .Orientation = xlPageField 
     .Position = 2 
    End With 
    With pt.PivotFields("Lead Status") 
     .Orientation = xlPageField 
     .Position = 3 
    End With 
    With pt.PivotFields("Lead Source") 
     .Orientation = xlPageField 
     .Position = 4 
    End With 
    With pt.PivotFields("Contact Owner:Full Name") 
     .Orientation = xlPageField 
     .Position = 5 
    With pt.PivotFields("Company: Company") 
     .Orientation = xlRowField 
     .Position = 1 
    End With 
    Next pt 
    Application.ScreenUpdating = True 
End Sub 
+4

你缺少結束後,隨着= .POSITION 5 – Absinthe

+1

多少'Withs'多少'結束Withs'你有嗎? – SJR

+1

第一行應該是'Sub test()'或任何你想要的子程序名稱以匹配'End Sub' – SBF

回答

0

您應該考慮在重複代碼時創建輔助函數。這將減少輸入錯誤,代碼混亂,並使代碼更易於閱讀和調試。

Object Browser Demo

使用對象瀏覽器,我會複製功能或對象參數和數據類型,我想傳遞給助手功能。通過這種方式,我可以在調用它時使用Intellisense。

Intellisense Demo


Sub Test() 
    Dim pt As PivotTable 
    Application.ScreenUpdating = False 
    For Each pt In ActiveSheet.PivotTables 
     setPivotFields pt, "Parent Company", xlPageField, 1 
     setPivotFields pt, "Milestone", xlPageField, 1 
     setPivotFields pt, "Lead Status", xlPageField, 2 
     setPivotFields pt, "Lead Source", xlPageField, 3 
     setPivotFields pt, "Contact Owner:Full Name", xlPageField, 4 
     setPivotFields pt, "Contact Owner:Full Name", xlPageField, 5 
     setPivotFields pt, "Company: Company", xlPageField, 1 
    Next pt 
End Sub 

Sub setPivotFields(pt As PivotTable, FieldName As String, Orientation As XlPivotFieldOrientation, Position As Variant) 
    With pt.PivotFields("Company: Company") 
     .Orientation = Orientation 
     .Position = Position 
    End With 
End Sub 
相關問題