【问题标题】:VBA Pass Form Controls to FunctionVBA 将表单控件传递给函数
【发布时间】:2016-04-10 01:45:53
【问题描述】:

全部,

我一直在为此苦苦挣扎:是否可以将对象传递给函数?

这是我想要完成的:

  1. 获取窗体上按下的控件的名称(作为对象?)
  2. 将控件的名称发送给函数“MyFunction”(作为参考?)
  3. 禁用“MyFunction”上的相同控件

form1 调用:

Private Sub button1_Click()
    Dim caller As String
    caller = Form1.ActiveControl.Name

    MyFunction(caller)

End Sub 'I'm able to pass it as a string

button1_Click 调用 MyFunction 并将 caller 传递给它:

Private Sub MyFunction(caller As String)
    caller.Enabled = False
End Sub

我知道这不能作为 字符串。作为一个真正的对象,我怎么可能做到呢? 谢谢!

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    将对象传递给子对象几乎没有问题:

    Private Sub Disable(c As Control)
        MsgBox c.Name
        c.Enabled = False
    End Sub
    
    Private Sub CommandButton1_Click()
        Disable CommandButton1
    End Sub
    
    Private Sub CommandButton2_Click()
        Disable CommandButton2
    End Sub
    
    Private Sub CommandButton3_Click()
        Disable CommandButton3
    End Sub
    

    在上面我创建了一个带有三个按钮的用户表单,它们会在单击时显示自己是谁,然后被禁用。

    注意

    Disable CommandButton1
    

    可以替换为

    Disable Me.ActiveControl
    

    甚至只是

    Disable ActiveControl
    

    【讨论】:

      【解决方案2】:

      您甚至可以像这样使用 Variant(粗略示例):

      Private Sub CommandButton1_Click()
          EnableDisable ActiveControl, "disable"
      End Sub
      
      Private Sub EnableDisable(control As Variant, status As String)
          If status = "enabled" Then
              control.Enabled = True
          Else
              control.Enabled = False
          End If
      End Sub
      

      不过,John Coleman 的例子比我的要好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-05
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 2020-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多