首页 > 解决方案 > 在 VBA 中执行用户窗体控件时对象不支持此属性错误

问题描述

我有一个 VBA 代码,用于查找用户窗体控件的类型并向我的 excel 表中的某些单元格添加注释。这些 Useform 控件是动态的。我的意思是,像文本框、标签等这样的控件是通过使用另一个宏插入的。它工作正常。我使用类似这种格式的东西来添加这些控件:: set Label1i = UserForm2.Controls.Add("Forms.Label.1", "Test" & labelCounter, True)。当我从同一用户窗体上的命令按钮调用下面的 sub 时。我收到“运行时 438 错误:对象不支持此属性或方法”

下面的代码运行成功。但是,当我向该程序添加一个手动“文本框”时,它显示了此错误。

Private Sub CommandButton1_Click()
Dim cCont As Control
Dim Commnts As String
Commnts = ""
For Each cCont In Me.Controls
    If TypeName(cCont) = "TextBox" And cCont <> "" Then
        Commnts = cCont
        Sheet1.Range(cCont.ControlTipText).AddComment Commnts
    End If

Next cCont

If Commnts <> "" Then
    Unload UserForm2
    MsgBox ("Comments updated")
    Call Graphic16_Click
Else
    MsgBox ("Nothing to update")
End If
End Sub

有人可以帮我解决这个问题。

标签: excelvba

解决方案


cCont <> ""

我收到“运行时 438 错误:对象不支持此属性或方法”

@SiddharthRout:是的。控件中已有图像。是的..是的..在介绍完之后,我去这个问题。– user3342652 7 分钟前

如果您的用户窗体上有一个没有默认属性的控件,您将收到该错误。例如一个Image控件。这个控件没有像Textbox/Range/CommanButtonetc 那样的默认属性。

你可以逃脱说

Debug.Print Textbox1
Debug.Print Range("A1")
Debug.Print Commandbutton1

但下面会出错

Debug.Print Image1 '<~~ This will give error 

因此,当您说 时cCont <> "",您正在尝试将 aString与控件的默认属性(在这种情况下没有)进行比较,因此您会收到错误消息Runtime 438 error: Object doesn't support this property or method

尝试处理错误,看看它在说什么确切的控制?

 Private Sub CommandButton1_Click()
    Dim cCont As Control

    On Error GoTo Whoa

    For Each cCont In Me.Controls
        If TypeName(cCont) = "TextBox" And cCont <> "" Then

        End If
    Next cCont

LetsContinue:

    Exit Sub
Whoa:
    MsgBox Err.Description & vbNewLine & _
           "Control Name : " & cCont.Name & _
           vbNewLine & _
           "Control Type : " & TypeName(cCont)
    Resume LetsContinue
End Sub

例如

在此处输入图像描述

解决方案

要处理此问题,请将其IF分成两部分,如下所示。If只有在满足第一个条件时才会检查第二个。

If TypeName(cCont) = "TextBox" Then
    If cCont <> "" Then

    End If
End If

推荐阅读