For loops to challange many form fields.

djkay2637

Registered User.
Local time
Today, 20:37
Joined
Nov 25, 2015
Messages
28
I am quite new to VB coding but I do understand some of the basics. I want to create a loop that checks the value within 8 text boxes and enabled a tick box next to the respected text box if it not blank. I am not quite sure on the syntax. I have 8 text boxes called Textbox1 : Textbox8 and 8 checkboxes with names checkbox1-8. This is the code I have already but I just need a bit of help with the syntax.

For i = 1 To 8 If Textbox(i) = "" Then
checkbox(i).enabled = false
else checkbox(i).enabled = true
End If
Next

I could just run 8 if statements and it does work but I know there must be a cleaner way with less lines of code.
 
Last edited:
For i = 1 To 8
me.controls("checkbox" & i).enabled = (trim(me.controls("textbox" & i).value & "") <> "")
Next
 
Thank you. Can I just ask.... What is the trim function needed for in this instance?
 
Last edited:
you can use the form's Current event:

Private Sub Form_Current()
For i = 1 To 8
me.controls("checkbox" & i).enabled = (trim(me.controls("textbox" & i).value & "") <> "")
Next
End Sub
 
Hi Arnelgp, Thank you for your replies so far. I did already put it within the form's current event and also on the field's after update event to test however no joy.

I have attempted it but it doesn't work for some reason. I think went onto try this but this too did not work.
For i = 1 To 8
If Me.Controls("textbox" & i) = "" Then
Me.Controls("textbox" & i).Value = False
end if
next
 
create a sub in your form and insert the code:

private sub subUpdateCheckBoxes()
Dim i As Integer
For i = 1 To 8
me.controls("checkbox" & i).enabled = (trim(me.controls("textbox" & i).value & "") <> "")
Next
End Sub

Now on your form's Load event:

Private sub Form_Load
Call subUpdateCheckBoxes
End Sub

on each of your textboxes' AfterUpdate events:

Private Sub textbox1_AfterUpdate()
Call subUpdateCheckBoxes
End Sub

Private Sub textbox2_AfterUpdate()
Call subUpdateCheckBoxes
End Sub

Private Sub textbox3_AfterUpdate()
Call subUpdateCheckBoxes
End Sub

... and so on ...
 
I have fixed it!!! using the NZ() function
For i = 1 To 8
If Nz(Me.Controls("RefName" & i), "") = "" Then
Me.Controls("RefName" & i & "Present").Enabled = False
Me.Controls("RefName" & i & "Present").Value = False
Else
Me.Controls("RefName" & i & "Present").Value = True
Me.Controls("RefName" & i & "Present").Enabled = True
End If
Next
 
I have been having so many issues where Access and VB wont handle null values. Once again. Thank you for your input. I did not know how to use the me.controls but now I do.
 

Users who are viewing this thread

Back
Top Bottom