我需要根据特定单元格的内容调整数据透视表。整个过程有效,但是当我刷新,添加或修改内容时,我收到以下错误消息:
Debug: Run_time error '1004': Method 'Intersect' of object '_Global' failed
这可能非常烦人,因为无论我在文件上做什么都会产生错误信息。
这是我使用的代码(在互联网上找到,而不是我自己的代码):
Option Explicit
Const RegionRangeName As String = "SuppName"
Const PivotTableName As String = "PivotTable1"
Const PivotFieldName As String = "SUPPLIER_NAME"
Public Sub UpdatePivotFieldFromRange(RangeName As String, FieldName As String, _
PivotTableName As String)
Dim rng As Range
Set rng = Application.Range(RangeName)
Dim pt As PivotTable
Dim Sheet As Worksheet
For Each Sheet In Application.ActiveWorkbook.Worksheets
On Error Resume Next
Set pt = Sheet.PivotTables(PivotTableName)
Next
If pt Is Nothing Then GoTo Ex
On Error GoTo Ex
pt.ManualUpdate = True
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim Field As PivotField
Set Field = pt.PivotFields(FieldName)
Field.ClearAllFilters
Field.EnableItemSelection = False
SelectPivotItem Field, rng.Text
pt.RefreshTable
Ex:
pt.ManualUpdate = False
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Public Sub SelectPivotItem(Field As PivotField, ItemName As String)
Dim Item As PivotItem
For Each Item In Field.PivotItems
Item.Visible = (Item.Caption = ItemName)
Next
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Not Intersect(Target, Application.Range(RegionRangeName)) _
Is Nothing Then
UpdatePivotFieldFromRange _
RegionRangeName, PivotFieldName, PivotTableName
End If
End Sub
代码中突出显示的部分是:
If Not Intersect(Target, Application.Range(RegionRangeName)) _
Is Nothing Then
我试图在这里和那里替换一些内容(例如ActiveWorksheet
或Sheet1
而不是Application
),但到目前为止没有成功。
答案 0 :(得分:1)
可能是因为Target和RegionRangeName-Region不在同一张纸上而出现问题?
Sub mytest()
'---Throws "run-time error '1004': Method 'Intersect' of object '_Global' failed"
MsgBox IIf(Intersect(Sheets(1).Range("G1"), _
Sheets(2).Range("G:AC")) Is Nothing, _
"No Intersect", "Intersects")
End Sub
我找到了这个例子here。如果不是这种情况,您可以使用本地窗口查找范围“Target”和“Application.Range(RegionRangeName)”的父项(即工作表),并查看它们在错误发生时是否相同抛出?