以对象为参数excel VBA调用子例程时发生运行时错误

时间:2018-08-04 06:34:35

标签: excel-vba arguments userform

场景

我有一个用户窗体,其中有一个带有某些选项的组合框。在相同的用户窗体中也有一个文本框。当我在组合框中选择某个选项时,我需要禁用文本框以及更改背景色。

我的代码

以下是我的代码。 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个对象)。有人知道原因吗?

1 个答案:

答案 0 :(得分:1)

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

方法1

调用子例程时需要添加调用

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

方法2

请勿在参数中使用括号。但是在这种情况下,不要在前面添加通话

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