2017-07-31 123 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。 –

相关问题