在单元格值更改上应用宏:1004错误

时间:2015-09-08 14:46:54

标签: excel vba excel-vba

我试图在单元格的值发生变化时应用宏。我在信息中心表中输入了这段代码:

Private Sub Worksheet_Change(ByVal Target As Range)
     If Not Intersect(Target, Target.Worksheet.Range("FilterChoice")) Is Nothing Then Call ApplyDashboardFilter
End Sub

触发器工作正常,宏立即执行,但不知道为什么我在高级过滤器功能上出错:"应用程序定义或对象定义的错误"

Option Explicit

Sub ApplyDashboardFilter()
    Dim rng As Range
    Dim filterName As String
    Dim tableName As String
    filterName = "Filter" & Replace(Sheets("Dashboard").Range("FilterChoice").Value, " ", "")
    tableName = filterName + "[#All]"
    Sheets("Dashboard").Activate
    Sheets("Dashboard").Columns("A:AN").Cells.Clear
    Sheets("Critical Flows").Range("ClosingFlows[#All]").AdvancedFilter Action:=xlFilterCopy _
        , CriteriaRange:=Sheets(filterName).Range(tableName) _
        , CopyToRange:=Sheets("Dashboard").Range("A1"), Unique:=False
    Set rng = Range(Range("A1"), Range("A1").CurrentRegion)
    ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes).Name = _
        "Flows" & filterName
    ActiveSheet.ListObjects("Flows" & filterName).TableStyle = "TableStyleMedium3"
    If Sheets("Dashboard").Range("FilterChoice").Value = "Orchestrated" Then
        Call ApplyFlormulaRunbookName
    End If
End Sub

当由仪表板表上的按钮触发时,宏工作。

我错过了什么吗?

提前致谢,

编辑:

好吧,发生了一些奇怪的事。我只是在休息后重新打开文件并它工作。 我怀疑ActiveSheet发生了一些事情和/或与另一个工作簿冲突,因为我正在使用其他2个工作簿和10个整体工作簿。

有可能吗?

1 个答案:

答案 0 :(得分:1)

我已添加了答案,因为评论不会允许我正确格式化。此代码仅引用工作表,而不是选择它们:

Sub ApplyDashboardFilter()
    Dim rng As Range
    Dim filterName As String
    Dim tableName As String
    Dim wrkShtDash As Worksheet
    Dim wrkShtFlows As Worksheet

    Set wrkShtDash = ThisWorkbook.Worksheets("Dashboard")
    Set wrkShtFlows = ThisWorkbook.Worksheets("Critical Flows")

    filterName = "Filter" & Replace(wrkShtDash.Range("FilterChoice").Value, " ", "")
    tableName = filterName + "[#All]"
    wrkShtDash.Columns("A:AN").Cells.Clear
    wrkShtFlows.Range("ClosingFlows[#All]").AdvancedFilter Action:=xlFilterCopy _
        , CriteriaRange:=ThisWorkbook.Worksheets(filterName).Range(tableName) _
        , CopyToRange:=wrkShtDash.Range("A1"), Unique:=False
    Set rng = wrkShtDash.Range(wrkShtDash.Range("A1"), wrkShtDash.Range("A1").CurrentRegion)
    wrkShtDash.ListObjects.Add(xlSrcRange, rng, , xlYes).Name = _
        "Flows" & filterName
    wrkShtDash.ListObjects("Flows" & filterName).TableStyle = "TableStyleMedium3"
    If wrkShtDash.Range("FilterChoice").Value = "Orchestrated" Then
        Call ApplyFlormulaRunbookName 'Spelt correctly?
    End If
End Sub

注意:我还没有对代码进行过测试,它只是表明您在使用之前不必激活工作表,并明确说明了哪些文件或工作表。使用 - ThisWorkbook表示VBA代码所在的文件。