对象名称在功能上发生变化

时间:2015-10-31 12:17:38

标签: vba excel-vba excel

我有一个获取Textbox数量的函数。我需要在对象的名字中使用这个数字。

Private Function func(ByVal number As Integer)
If Val(TextBox[number].Text) > 300 Then
    TextBox[number].Text = 300
End If
End Function

E.g。如果number为5则应为:TextBox5.Text = 300

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

此函数会根据其名称为您提供控件:

Private Function GetControlByName(name As String) As Object
    Dim obj As Object
    For Each obj In Me.Controls
        If obj.Name = name Then
            Set GetControlByName = obj
            Exit Function
        End If
    Next
End Function

然后这个子做了你想要的,但它会失败它你真的没有一个名为TextBoxN的文本框,其中N是你提供的数字

Private Sub func(ByVal N As Integer)
    Dim t As Object
    Set t = GetControlByName("TextBox" & N)
    If val(t.Text) > 300 Then t.Text = "300"
End Sub