How to get a name of control by name?

后端 未结 2 1464
暗喜
暗喜 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:33

    I'm not sure how you are calling this, but here's a self-contained procedure that should help:

    Sub test()
    
    Dim ws As Excel.Worksheet
    Dim ProductCombo As OLEObject
    Dim ProductText As OLEObject
    
    Set ws = ThisWorkbook.Sheets(1)
    With ws
        Set ProductCombo = .OLEObjects("Product1")
        Set ProductText = .OLEObjects(ProductCombo.Name & "_status")
        ProductText.Enabled = ProductCombo.Object.Text <> "Disabled"
    End With
    End Sub
    

    EDIT: I really hate worksheet controls - I start from scratch every time I program them! Nonetheless, I thought I'd add this subroutine which resets every textbox whose name fits the patter Product#_status, according to its paired combobox. The logic does assume the names start with Product1, Product2, etc., without a gap in the numbering:

    Sub test2()
    
    Dim ws As Excel.Worksheet
    Dim ctl As OLEObject
    Dim i As Long
    Dim ProductComboboxesCount
    Dim ProductCombo As OLEObject
    Dim ProductText As OLEObject
    Const ControlPrefix As String = "Product"
    
    Set ws = ThisWorkbook.Sheets(1)
    With ws
        For Each ctl In .OLEObjects
            If TypeOf ctl.Object Is MSForms.ComboBox And Left(ctl.Name, Len(ControlPrefix)) = ControlPrefix Then
                ProductComboboxesCount = ProductComboboxesCount + 1
            End If
        Next ctl
        For i = 1 To ProductComboboxesCount
            Set ProductCombo = .OLEObjects(ControlPrefix & i)
            Set ProductText = .OLEObjects(ControlPrefix & i & "_status")
            ProductText.Enabled = ProductCombo.Object.Text <> "Disabled"
        Next i
    End With
    End Sub
    

提交回复
热议问题