Access VBA - How would I have a loop in VBA that allows me to loop through control names

前端 未结 3 1865
暗喜
暗喜 2020-12-11 04:39

I have about 10 text boxes on a form that are actually used for display not entry. They are are named txt_001_Name, txt_002_Title, etc..what kind o

3条回答
  •  没有蜡笔的小新
    2020-12-11 04:46

    You can list the names of textbox controls with a simple procedure like this:

    Public Sub TextBoxNames(ByRef pfrm As Form)
        Dim ctl As Control
        For Each ctl In pfrm.Controls
            If ctl.ControlType = acTextBox Then
                Debug.Print ctl.Name
            End If
        Next ctl
        Set ctl = Nothing
    End Sub
    

    You could call it from the form's Load event:

    Private Sub Form_Load()
        TextBoxNames Me
    End Sub
    

    However, I don't understand what you're trying to accomplish. I realize you want to do something with ctl.Name other than Debug.Print, but I don't know what that is.

    Rather than computing a result for me.txt_001_result and then assigning that value to the text box, consider setting the control source for txt_001_result to txt_001_value / txt_001_calc and let Access put the proper value into txt_001_result for you.

    In response to your comments, I'll suggest this procedure as a starting point for you to build upon:

    Public Sub MyTextBoxValues()
        Const cintLastTextBoxNum As Integer = 10
        Dim i As Integer
        Dim strValueControl As String
        Dim strCalcControl As String
        Dim strResultControl As String
        Dim strPrefix As String
    
        For i = 1 To cintLastTextBoxNum
            strPrefix = "txt_" & Format(i, "000")
            'txt_001_value      txt_001_calc     txt_001_result '
            strValueControl = strPrefix & "_value"
            strCalcControl = strPrefix & "_calc"
            strResultControl = strPrefix & "_result"
            'me.txt_001_result = me.txt_001_value / me.txt_001_calc '
            'Debug.Print strResultControl, strValueControl, strCalcControl '
            Me.Controls(strResultControl) = Me.Controls(strValueControl) / _
                Me.Controls(strCalcControl)
        Next i
    End Sub
    

提交回复
热议问题