【问题标题】:Runtime error when calling a subroutine with an object as argument excel vba调用以对象为参数的子例程时出现运行时错误excel vba
【发布时间】:2020-07-08 04:38:51
【问题描述】:

场景

我有一个用户表单,它有一个带有一些选项的组合框。在同一个用户表单中也有一个文本框。当我在组合框中选择某个选项时,我需要禁用文本框并更改背景颜色。

我的代码

以下是我的代码。 poType 是组合框名称,unitPrice 是文本框名称

Public Sub poType_Change()    
    If mainPage.poType.Value = "FOC" Then
        disabling (unitPrice)
    Else
        enabling (unitPrice)
    End If
End Sub

以下是子程序的禁用和启用

Sub disabling(ByVal objectToDisable As Object)
    objectToDisable.Enabled = False
    objectToDisable.BackColor = &H80000003
End Sub

Sub enabling(ByVal objectToEnable As Object)
    objectToEnable.Enabled = True
    objectToEnable.BackColor = &H80000005
End Sub

但是,当我执行此代码时,它显示运行时错误(需要 424 个对象)。谁知道原因?

【问题讨论】:

  • 为什么 poType_Change 是公开的?什么是主页面?是那种形式吗?
  • poType_Change 是公开的。 mainPage 是放置组合框和文本框的用户窗体
  • 调用 Sub 时不要使用括号
  • 对,去掉“( ...)”。它会将对象评估为默认值,即文本框的值。您还应该将 mainPage 替换为 Me。
  • @TimWilliams 谢谢。它用上面的代码解决了我的问题

标签: excel vba arguments userform


【解决方案1】:

能够找到此问题的根本原因。上述问题可以通过两种方式解决

方法一

调用子程序时需要添加call

Public Sub poType_Change()    
    If mainPage.poType.Value = "FOC" Then
        call disabling (unitPrice)
    Else
        call enabling (unitPrice)
    End If
End Sub

Sub disabling(ByVal objectToDisable As Object)
    objectToDisable.Enabled = False
    objectToDisable.BackColor = &H80000003
End Sub

Sub enabling(ByVal objectToEnable As Object)
    objectToEnable.Enabled = True
    objectToEnable.BackColor = &H80000005
End Sub

方法二

不要在参数中使用括号。但是对于这种情况,不要在前面加call

Public Sub poType_Change()    
    If mainPage.poType.Value = "FOC" Then
        disabling unitPrice
    Else
        enabling unitPrice
    End If
End Sub

Sub disabling(ByVal objectToDisable As Object)
    objectToDisable.Enabled = False
    objectToDisable.BackColor = &H80000003
End Sub

Sub enabling(ByVal objectToEnable As Object)
    objectToEnable.Enabled = True
    objectToEnable.BackColor = &H80000005
End Sub

【讨论】:

  • 我建议也将 mainPage 替换为 Me!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
相关资源
最近更新 更多