6

我有一个简单的功能,其中有一个组合框。如果组合框的值等于“禁用”,我将禁用文本框 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

我该怎么做呢?

4

2 回答 2

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
于 2012-09-08T20:48:50.327 回答
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
于 2012-09-08T19:50:56.590 回答