“Method or Data Member Not Found” when Dim'ing Worksheet as Worksheet but not Variant

ぃ、小莉子 提交于 2020-02-02 05:45:09

问题


Consider this simple example. In a new sheet create a ActiveX Checkbox called Checkbox1

Try the following two subroutines. The first does not compile with a "Method or Data Member Not Found" error, the second one works fine.

Why doesn't the first example work?

Option Explicit

Sub DoesntWork()
Dim ws As Worksheet
Set ws = Worksheets(1)

MsgBox "Checkbox state is: " + CStr(ws.CheckBox1.Value)

End Sub

Sub Works()
Dim ws As Variant
Set ws = Worksheets(1)

MsgBox "Checkbox state is: " + CStr(ws.CheckBox1.Value)

End Sub

回答1:


The problem is with the line ws.CheckBox1.Value. You can't use it like this and hence you are getting that error. Try this

Sub Sample()
    Dim ws As Worksheet
    Dim objole As OLEObject

    Set ws = Worksheets(1)

    Set objole = ws.OLEObjects("CheckBox1")

    MsgBox "Checkbox state is: " & objole.Object.Value
End Sub

If you want to use the Object directly then you can also use this

Sub Sample()
    Dim ws As Worksheet

    Set ws = Worksheets(1)

    MsgBox "Checkbox state is: " & Worksheets(ws.Name).CheckBox1.Value
End Sub


来源:https://stackoverflow.com/questions/31840548/method-or-data-member-not-found-when-diming-worksheet-as-worksheet-but-not-va

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