How to get a name of control by name?

后端 未结 2 1476
暗喜
暗喜 2020-12-19 08:42

I have a simple function where there\'s a combo box. If combo box\'s value is equal to \"Disable\", I\'ll disable textbox B. There are many combo boxes with their correspond

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-19 09:18

    VBA

    Edit: (Change for an actual VBA macro)

    Sub Macro1()
    '
    ' GetControl By Name
    '
        If value_of_a = "disable" Then
            GetControl(ComboBox1.Name + "_status").Enabled = False
        End If
    
    End Sub
    
    Function GetControl(nameOfControl As String) As OLEObject
        Dim ctrl As OLEObject
    
        For Each ctrl In ActiveSheet.OLEObjects
            If ctrl.Name = nameOfControl Then
                Set GetControl = ctrl
            End If
        Next ctrl
    End Function
    

    VB.Net

    Code for VB.Net if anyone wants it for that reason:

    Sub Main()
        If value_of_a = "disable" Then 
            GetControl(ComboBox_1.Name + "_status").Enabled = False
        End If
    End Sub
    
    Function GetControl(nameOfControl As String) As Control
        For Each ctrl In Me.Controls
            If ctrl.Name = nameOfControl Then
                Return ctrl
            End If
        Next ctrl
    
        Return Nothing
    End Function
    

提交回复
热议问题