Search code examples
excelvbaargumentsuserform

Runtime error when calling a subroutine with an object as argument excel vba


Scenario

I have a userform whereby it has a Combobox with some options. There is a Textbox as well in the same userform. When I select a certain option in the combobox, I need the text box to be disabled as well as change background colour.

My Codes

Following are my codes. poType is the combobox name and unitPrice is the textbox name

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

Following is the subroutines disabling and enabling

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

However, it is showing runtime error (424 object required) when I am executing this code. Anyone knows the reason?


Solution

  • Able to find rootcause of this problem. The above problem can be solved in two ways

    Method 1

    Need to add call when calling a subroutine

    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
    

    Method 2

    Don't use parenthesis for arguments. But for this case, don't add call in front

    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