如何通过名称获取控件名称?

时间:2012-09-08 19:28:34

标签: excel vba

我有一个简单的功能,其中有一个组合框。如果组合框的值等于“禁用”,我将禁用文本框B.有许多组合框及其对应的文本框B,按行排列并手动命名。如果组合框A的名称为Product1,则文本框B将命名为Product1_status

我在想这样的事情:

If value_of_a = "disable" Then 
 Dim name_of_b as String
 name_of_b = Me.Combo.Name + "_status"
 get_object_by_name(name_of_b).Enabled = False
End If

我该怎么做?

2 个答案:

答案 0 :(得分:5)

我不确定你是怎么称呼它的,但这是一个应该有用的独立程序:

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
编辑:我真的很讨厌工作表控件 - 每次编程时我都会从头开始!尽管如此,根据配对的组合框,我想我会添加这个子程序来重置每个文本框的名称都适合模式Product#_status。逻辑确实假设名称以Product1,Product2等开头,编号中没有间隙:

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

答案 1 :(得分:3)

VBA

编辑:(更改实际的VBA宏)

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

VB.Net的代码,如果有人因为这个原因需要它:

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