问题
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