Name of object changes in function

2019-09-02 18:54发布

I have a function that gets the number of Textbox. I need to use this number in object's name.

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

E.g. if number is 5 it should be: TextBox5.Text = 300

Thanks for help!

1条回答
相关推荐>>
2楼-- · 2019-09-02 19:17

This function gets you a control given its name:

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

Then this sub does what you want, but it will fail it you dont really have some textbox called TextBoxN, where N is the number you provide

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
查看更多
登录 后发表回答