运行时错误的类型

时间:2016-04-26 10:47:01

标签: excel excel-vba runtime-error vba

以下代码给出了这个错误: Class does not support automation or does not support expected interface

任何人都可以解释为什么我会收到此错误

Sub typeofcheck()
Dim wks As New Worksheet

If TypeOf wks Is Worksheet Then
    MsgBox "This is Worksheet"
Else
    MsgBox "This is not"
End If
End Sub

3 个答案:

答案 0 :(得分:2)

问题出在As New

AFAIK您无法直接创建工作表的新实例;您必须在Add集合中调用Sheets方法,例如:

Public Sub typeofcheck()
    Dim wks As Worksheet
    Set wks = ActiveWorkbook.Sheets.Add

    If TypeOf wks Is Worksheet Then
        MsgBox "This is Worksheet"
    Else
        MsgBox "This is not"
    End If
End Sub

答案 1 :(得分:0)

不确定是否可以解释,但我认为您可以通过初始化变量wks来修复代码。像这样的东西

Sub typeofcheck()
Dim wks As New Worksheet
Set wks = Sheets("someFunnySheetName")


If TypeOf wks Is Worksheet Then
    MsgBox "This is Worksheet"
Else
    MsgBox "This is not"
End If
End Sub

恕我直言,问题在于DIM您只需要一些内存,而Set则会设置数据类型。但VBA是一种谜。有一次我试着在MSDN文档中读到一些内容,而且它比地狱更糟......

edit1:我做了一些进一步的测试,你提到的这个漂亮的错误信息听起来非常专业,但如果你调试代码,并将鼠标悬停在wks变量上,它会告诉你wks = <Object variable or With block variable not set>哪个更容易读。因此,对于未来,尝试调试,并将您的变量悬停。如果你不知道该怎么做,那就试试Set s :) VBA是关于魔法的

答案 2 :(得分:0)

错误是由尝试访问an interface that isn't available引起的。

正确的做法是:

Sub typeofcheck()
Dim wks As Worksheet
Set wks = Worksheets.Add

Debug.Print TypeOf wks Is Worksheet
If TypeOf wks Is Worksheet Then
    MsgBox "This is Worksheet"
Else
    MsgBox "This is not"
End If
End Sub