【问题标题】:What's happening in this line?这条线发生了什么?
【发布时间】:2016-10-25 00:11:28
【问题描述】:

我创建了一个带有复选框的名为“questionario”的表单,并制作了一个 IF 语句,如果所有复选框都是空白的,则发送一个 msgbox。但是当我运行宏时,引用的行中会出现错误(错误 438)。

Private Sub CommandButton1_Click()

Dim ind As Integer
Dim cont As MSForms.Control
ind = 0

If questionario.resp1.Value = True Then
Range("E8").Value = Range("E8").Value + 1
End If
If questionario.resp2.Value = True Then
Range("F8").Value = Range("F8").Value + 1
End If
If questionario.resp3.Value = True Then
Range("G8").Value = Range("G8").Value + 1
End If


For Each cont In questionario.Controls

If (TypeName(cont) = "CheckBox") And (cont.Value = True) Then

ind = ind + 1

End If
Next


If ind = 0 Then
MsgBox "mmm"
Else
questionario.Hide
Set questionario = Nothing
End If

End Sub

【问题讨论】:

  • 你可以试试If cont.TypeName = ... 吗?
  • 我试过了,但我认为问题出在And (cont.Value = True) 部分

标签: excel vba userform


【解决方案1】:

将您的支票分为两个步骤:

For Each cont In questionario.Controls
    If TypeName(cont) = "CheckBox" Then
        If cont.Value Then '<-- a checkbox control has a Value property
            ind = ind + 1
            Exit For '<-- no need to go on
        End If
    End If
Next

原因是某些控件类型没有.Value 属性,而VBA 没有短路布尔表达式。因此,即使cont.TypeName "CheckBox",表达式仍然会尝试查询那些可能没有此类属性的控件的.Value 属性。

【讨论】:

  • 我不会添加作为答案,因为这个答案可以解决问题。例如,标签没有Value 属性,因此会引发错误。编辑:user3598756 现在已经解决了这个问题。 :)
  • 成功了,谢谢!你知道为什么我不分两步就不行吗?
  • 谢谢@DarrenBartrup-Cook
  • 不客气。这是因为我在评论中添加的内容(可能过于简洁)并且@DarrenBartrup-Cook 更详细地清除了:并非所有用户窗体控件都具有Value 属性,而If (TypeName(cont) = "CheckBox") And (cont.Value = True) Then 语句将检查这两个条件以返回其结果,因此尝试访问ControlValue 属性,即使TypeName(cont) = "CheckBox" 部分将返回False
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多