Get worksheet property using worksheet variable

不问归期 提交于 2020-01-14 01:34:08

问题


I apologize if this has already been answered, but I had no luck searching on this.

What’s the best way to access a worksheet property, when the worksheet is referenced by a variable?

This one raises a compile error:

Sub Tst1(Wk As Worksheet)
    Debug.Print Wk.pbOK
End Sub

This one works, but is there a better way? Thanks.

Sub Tst2(Wk As Object)
    Debug.Print Wk.pbOK
End Sub

回答1:


With a tip from KazJaw, found out that you can get it compile no issues if:

Sub Tst1(Wk As Worksheet)
    Debug.Print Thisworkbook.Worksheets(Wk.Name).pbOK
End Sub

The only usefulness of this method i can think of is to store the state of macro processed (or mark worksheet as processed at a session), as values does not get saved after the workbook is re-opened.




回答2:


I would say combine the two of them. The advantage of the first is that it preserves the Type Safety of the function. The advantage of the second is that it works. :)

Try keeping the parameter as a Worksheet, but cast it to an object (using a temp variable, it only costs a 4 byte pointer/copy) before you ask about the property:

Public Sub Test1(Wk As Worksheet)
    Dim tempObj As Object
    Set tempObj = Wk
    Debug.Print tempObj.pbOk
End Sub

I know this is supposed to be an answer and not a question, but can anyone tell my why VBA doesn't seem to have CObj() so the worksheet could be cast directly without the temp variable? I would have used that but it wasn't recognized. VB only perhaps?



来源:https://stackoverflow.com/questions/19799875/get-worksheet-property-using-worksheet-variable

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