简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM