ActiveSheet vs. WorkSheet

这一生的挚爱 提交于 2019-12-22 18:34:17

问题


I'm using Excel for Mac 2011, and I have a couple Check Boxes in one sheet. I'm trying to automate them with the following code:

Private Sub CheckBox12_Click()
    Dim ws As Worksheet
    Set ws = ActiveSheet
    With ws
        If .Shapes("CheckBox12").OLEFormat.Object.Value = xlOn Then
           .Range("CK1").EntireColumn.Hidden = False
       Else
           .Range("CK1").EntireColumn.Hidden = True
       End If
   End With
End Sub

This code gives me the error: Run-time error 445 Object does not support this action.

However if remove ws and just do

Private Sub CheckBox12_Click()
    With ActiveSheet
         If .Shapes("CheckBox12").OLEFormat.Object.Value = xlOn Then
            .Range("CK1").EntireColumn.Hidden = False
         Else
            .Range("CK1").EntireColumn.Hidden = True
        End If
    End With
End Sub

This works just fine.

What's the deal here? I know I can just use ActiveSheet, but I always like to first set it = ws because it gives the dropdown list of properties/methods as I code.


回答1:


I think you're getting a compiler error rather than a run-time error.

I suspect the reason ActiveSheet works is because the compiler doesn't check it. On the other hand, ws doesn't work because the compiler is trying to parse it and actually has a false flag. So the compiler checker has an error. It is flagging an error that actually should not be an error.

Object doesn't support this action (Error 445)

EDIT: Also try this and let me know if it works:

Dim ws As Object
Set ws = ActiveSheet
With ws
    ...

It is also worth noting that ActiveSheet and Worksheet are not the same thing. ActiveSheet can also include a ChartSheet; but a ChartSheet can never be a Worksheet. So maybe it's not surprising that there are differences between With ws and With ActiveSheet.

Another thing you should try is setting your object to a variable:

Dim ws As Worksheet
Set ws = ActiveSheet
Dim chk As Object
With ws
    Set chk = .Shapes("CheckBox12").OLEFormat.Object
    If chk.Value = xlOn Then
        .Range("CK1").EntireColumn.Hidden = False
    Else
        .Range("CK1").EntireColumn.Hidden = True
    End If
End With

This may remove the ws variable from the equation. Of course it would be better to dim as the correct object rather than using the generic as Object but I'm not sure what it would be.



来源:https://stackoverflow.com/questions/24739448/activesheet-vs-worksheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!