2017-07-31 261 views
2

我的代碼有些問題。我想用VBA按鈕選擇開始日和結束一天。使用VBA Excel選擇開始日期 - 結束日期

這是我的代碼。有人可以幫助我嗎?非常感謝...

(抱歉我的英文不好)。

我的代碼:

Sub CARI() 
Dim objname As String 
Dim jumpv As Integer 
Dim I As Integer 
Dim S1 As Date 
Dim S2 As Date 

Application.DisplayAlerts = False 
Application.ScreenUpdating = False 

Sheets("Dashboard").Select 
objname = Cells(5, 5).Value 
S1 = Cells(6, 4).Value 
S2 = Cells(6, 9).Value 
jumpv = 4 

Worksheets("PV").Activate 
For I = 4 To jumpv 
    Application.StatusBar = "Loading.. (" & Round(I/jumpv * 100, 0) & ")%" 

     Sheets("PV").Select 
     ActiveSheet.PivotTables("PV" & I).PivotFields("REGION").ClearAllFilters 
     ActiveSheet.PivotTables("PV" & I).PivotFields("REGION").CurrentPage = objname 
     ActiveSheet.PivotTables("PV" & I).PivotFields("DAY").ClearAllFilters 
     ActiveSheet.PivotTables("PV" & I).PivotFields("DAY").PivotFilters.Add _ 
     Type:=xlDateBetween, Value1:=S1, Value2:=S2 
     ActiveSheet.PivotTables("PV" & I).PivotFields("DAY").AutoSort _ 
     xlAscending, "DAY" 
Next I 
Sheets("Dashboard").Select 
Application.StatusBar = "" 
MsgBox "Done!" 
End Sub 

capture PV table

+2

「我有一些麻煩,我的代碼」>什麼問題是什麼?你有什麼具體的錯誤嗎? –

+0

錯誤「無法獲取工作表類的pivottables屬性。」 (PV「&I).PivotFields(」REGION「)。ClearAllFilters –

回答

1

嘗試代碼註釋中下面的代碼,解釋:

Option Explicit 

Sub CARI() 

Dim objname As String 
Dim jumpv As Integer 
Dim I As Integer 
Dim S1 As Date 
Dim S2 As Date 

Application.DisplayAlerts = False 
Application.ScreenUpdating = False 

With Sheets("Dashboard") ' <-- use With instead of Activate or Select the sheet 
    objname = .Cells(5, 5).Value 
    S1 = .Cells(6, 4).Value 
    S2 = .Cells(6, 9).Value 
End With 

jumpv = 4 

With Worksheets("PV") 
    For I = 4 To jumpv 
     Application.StatusBar = "Loading.. (" & Round(I/jumpv * 100, 0) & ")%" 

     .PivotTables("PV" & I).PivotFields("REGION").ClearAllFilters 
     .PivotTables("PV" & I).PivotFields("REGION").CurrentPage = objname 
     .PivotTables("PV" & I).PivotFields("DAY").ClearAllFilters 

     ' when filtering dates, safest way is to covert to Double (their actual value, not their format) 
     .PivotTables("PV" & I).PivotFields("DAY").PivotFilters.Add _ 
       Type:=xlDateBetween, Value1:=CDbl(S1), Value2:=CDbl(S2) 
     .PivotTables("PV" & I).PivotFields("DAY").AutoSort xlAscending, "DAY" 
    Next I 
End With 

Sheets("Dashboard").Select 

Application.StatusBar = "" 
Application.DisplayAlerts = True 
Application.ScreenUpdating = True 
MsgBox "Done!" 

End Sub 
+0

感謝您的回答,但仍然在此conde上進行調試 .PivotTables(」PV「&I).PivotFields(」REGION「)。 ClearAllFilters –

+0

@SeptianaFajrin你確定你有一個名爲「REGION」的'PivotField'?驗證你的拼寫(或額外的空格) –

+0

是的,我已經在工作表「PV」上已經命名爲「REGION」的PivotField。 –

相關問題