Search code examples
formsms-accesstextbox

How to update another text box while typing in access 2007 form?


I have a few text boxes which have to be filled with numeric values from 0 to 100. Below them there is another text box which stands for a total (the sum of the values from the text boxes above). How can I update the sum text box while typing in any of the other text boxes above?


Solution

  • This is problematic due to the asinine requirement in Access that you have to set focus to text areas before you can get their value. I would recommend you change your design so that the text field is updated in response to a button click instead of on change.

    If you want to go the update-on-change route, you would attach change events to each of the addend text fields. The event handlers would need to save the caret position/selection length, update the sum in the output text field, and restore the caret position. You need to save/restore the caret position because this is lost when the focus changes.

    Here's an example for two text fields (txt1 and txt2). The output field is named txtOutput.

    Private Sub txt1_Change()
        Dim caret_position As Variant
    
        caret_position = Array(txt1.SelStart, txt1.SelLength)
    
        UpdateSum
    
        txt1.SetFocus
        txt1.SelStart = caret_position(0)
        txt1.SelLength = caret_position(1)
    End Sub
    
    Private Sub txt2_Change()
        Dim caret_position As Variant
    
        caret_position = Array(txt2.SelStart, txt2.SelLength)
    
        UpdateSum
    
        txt2.SetFocus
        txt2.SelStart = caret_position(0)
        txt2.SelLength = caret_position(1)
    End Sub
    
    Private Sub UpdateSum()
        Dim sum As Variant
        sum = CDec(0)
    
        txt1.SetFocus
        If IsNumeric(txt1.Text) Then
            sum = sum + CDec(txt1.Text)
        End If
    
        txt2.SetFocus
        If IsNumeric(txt2.Text) Then
            sum = sum + CDec(txt2.Text)
        End If
    
        txtOutput.SetFocus
        txtOutput.Text = sum
    End Sub