必须参考活动工作表错误

时间:2016-06-01 19:24:57

标签: excel excel-vba vba

我在最后一行收到reference must be on the active sheet error

For Each ws In tabArr()

With ws

    Select Case .Name
        Case "Summary"
            area = "PRNSUMMARY"
            title = "$1:$9"
        Case "Monthly CC Sum"
            area = "PRNMONTHLYCCSUM"
            title = "$2:$16"
        Case .Name = "Div Sal Sum"
            area = "PRNDIVSALSUM"
            title = ""
        Case .Name = "CC Sal Sum"
            area = "PRNCCSALSUM"
            title = "$2:$16"
    End Select

    With .PageSetup
        .PrintArea = area '<----error here

我尝试过创建一个worksheet对象。

Dim ws As Worksheet
For Each e In tabArr()

Set ws = e
Debug.Print ws.Name
With ws
...

但仍然失败:/真奇怪的是,它打印出第一张工作表。只在第二次失败。

2 个答案:

答案 0 :(得分:3)

在前2个Case语句中,您有一个文字字符串。在第3和第4 Case次陈述中,您有.Name = literal

答案 1 :(得分:1)

显然为时已晚,但我想出了一个通用的可重复示例来重新创建错误。

基本上查看全局vs本地范围命名范围。如果命名范围引用错误的工作表,或者工作表特定的命名范围是错误工作表的本地,则重新创建错误。

显然不是问题,但我想我会分享。

Sub test1()

'Everything declared for sheet2 works fine
ActiveWorkbook.Names.Add Name:="Print_Scope_Global", RefersTo:="=Sheet2!$A$1:$D$1"
ActiveWorkbook.Sheets("sheet2").Names.Add Name:="Print_Scope_Sheet", RefersTo:="=Sheet2!$A$1:$D$1"

pArea = "Print_Scope_Sheet"
Sheets("Sheet2").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With
Sheets("Sheet1").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With

pArea = "Print_Scope_Global"
Sheets("Sheet2").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With
Sheets("Sheet1").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With


End Sub

Sub test2()

'Named range refers to wrong sheet
ActiveWorkbook.Names.Add Name:="Print_Scope_Global", RefersTo:="=Sheet1!$A$1:$D$1"
ActiveWorkbook.Sheets(2).Names.Add Name:="Print_Scope_Sheet", RefersTo:="=Sheet1!$A$1:$D$1"

pArea = "Print_Scope_Sheet"
Sheets("Sheet2").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With
Sheets("Sheet1").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With

pArea = "Print_Scope_Global"
Sheets("Sheet2").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With
Sheets("Sheet1").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With


End Sub

Sub test3()

'Name range is local to the wrong sheet
ActiveWorkbook.Sheets("sheet1").Names.Add Name:="Print_Scope_Sheet", RefersTo:="=Sheet2!$A$1:$D$1"

pArea = "Print_Scope_Sheet"
Sheets("Sheet2").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With
Sheets("Sheet1").Activate
With Sheets("Sheet2")
    With .PageSetup
        .PrintArea = pArea
    End With
End With

End Sub