我有一些VBA代碼,它設置爲查找動態(更改)的數據表,代碼然後更改範圍以適應數據透視表,並刷新基於新範圍的數據透視表。Excel VBA - 輸入過濾器到數據透視表返回對象需要
代碼一直運行,直到它到達需要應用過濾器的部分。我有一個日期值,我已經聲明一個字符串稱爲PivotFilter,當代碼去應用過濾器,我得到一個運行時錯誤1004 - 應用程序定義或對象定義的錯誤
我一直在試圖找出在過去的兩個小時內,似乎無法解決它,我試圖將字符串更改爲一個範圍,這也沒有奏效。有什麼建議麼?
編輯 修正錯誤區段的錯字,我仍然得到應用程序定義或對象定義的錯誤
Sub PortfolioDataLoad()
Dim wb1 As Workbook
Dim ws1, ws2, ws3, ws4, ws5 As Worksheet
Dim r1, r2, r3 As Range
Dim StartPoint, DataRange As Range
Dim PivotName, Pivotname2, Pivotname3, Pivotname4 As String
Dim Datefrom, Dateto As Range
Dim PivotFilter As String
PivotFilter = Worksheets("Configuration").Range("B1")
PivotName = "PivotTable3"
Pivotname2 = "PivotTable4"
Pivotname3 = "PivotTable5"
Pivotname4 = "PivotTable1"
Application.StatusBar = "Transforming data into report graphs..."
'Set Variables Here
Set wb1 = ThisWorkbook
Set ws1 = wb1.Sheets("Control Sheet")
Set ws2 = wb1.Sheets("Program Data")
Set ws3 = wb1.Sheets("Configuration")
Set ws4 = wb1.Sheets("Overview")
If ws1.Visible = False Then
ws1.Visible = True
End If
'Dynamically Retrieve Data from Program Data
Set StartPoint = ws2.Range("A1")
Set DataRange = ws2.Range(StartPoint, StartPoint.SpecialCells(xlLastCell))
NewRange = ws2.Name & "!" & _
DataRange.Address(ReferenceStyle:=xlR1C1)
If WorksheetFunction.CountBlank(DataRange.Rows(1)) > 0 Then
MsgBox "One of your data columns in the 'Program Data' tab has a blank heading." & vbNewLine _
& "Please fix and re-run!.", vbCritical, "Column Heading Missing!"
Exit Sub
End If
'Change Pivot Range to Cache set above
ws3.PivotTables(PivotName).ChangePivotCache _
ThisWorkbook.PivotCaches.Create(_
SourceType:=xlDatabase, _
SourceData:=NewRange)
ws3.PivotTables(Pivotname2).ChangePivotCache _
ThisWorkbook.PivotCaches.Create(_
SourceType:=xlDatabase, _
SourceData:=NewRange)
ws3.PivotTables(Pivotname3).ChangePivotCache _
ThisWorkbook.PivotCaches.Create(_
SourceType:=xlDatabase, _
SourceData:=NewRange)
ws3.PivotTables(Pivotname4).ChangePivotCache _
ThisWorkbook.PivotCaches.Create(_
SourceType:=xlDatabase, _
SourceData:=NewRange)
'Refresh Tables
ws3.PivotTables(PivotName).RefreshTable
ws3.PivotTables(Pivotname2).RefreshTable
ws3.PivotTables(Pivotname3).RefreshTable
ws3.PivotTables(Pivotname4).RefreshTable
'Set Date in Pivot Table Filter - Results in Run-time error '424': Object Required
ws3.PivotTables(PivotName).PivotFields("Planning Month").PivotFilters.Add _
Type:=xlBeforeOrEqualTo, Value1:=PivotFilter
ws3.PivotTables(Pivotname2).PivotFields("Planning Month").PivotFilters.Add _
Type:=xlBeforeOrEqualTo, Value1:=PivotFilter
ws3.PivotTables(Pivotname4).PivotFields("Planning Month").PivotFilters.Add _
Type:=xlBeforeOrEqualTo, Value1:=PivotFilter
End Sub
道歉,我只是修正了錯字但我仍然得到應用程序定義或定義的對象錯誤 – PootyToot 2014-10-27 05:21:05
謝謝你這些,我已經改變了聲明更明確的像你上面顯示,有我的透視表過濾器中的計劃月份值,但仍顯示相同的錯誤。 難道是代碼引用的特定日期格式爲dd/mm/yy的單元格值? (澳大利亞日期系統) – PootyToot 2014-10-27 23:09:29