【发布时间】:2014-10-27 04:53:18
【问题描述】:
我有一些 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
【问题讨论】: