Checking and Unchecking Checkboxes in Access - vba

I have a form in MS Access with multiple checkboxes which I want to use to fill up one textbox. If one of the checkboxes gets unchecked, I want its value to be deleted from the textbox without deleting other values. I'm new at using Access and coding in VBA (been reading ebooks for the past 3 weeks) and although I've tried to do research online it's been difficult for me to find the right code.
This is what I have so far:
First code found
Private Sub cb_click()
If Me.cb1 = True Then
Me.txtComentarios.Value = "INACTIVO;"
Else
Me.txtComentarios.Value = Null
End If
End Sub
Second code found
Private Sub cb2_Click()
If Me.cb2 = -1 Then
Me.[txtComentarios] = [txtComentarios] & "DISCREPANCIA"
Else
Me.[txtComentarios] = ""
End If
Exit Sub
End Sub
Also I would like for the checkboxes to fill the textbox in the same order the chechboxes are displayed.
Ex.
cb1; cb2; cb3
If, cb2 gets unchecked and its value gets deleted, I should have "cb1; cb3" but if I re-check cb2 I should get "cb1; cb2; cb3" again.
I just hope someone could guide me in. Thank you in advance.
Luz

You don't need events for each checkbox. Just create one procedure, which creates full text depending on checkboxes state and puts this text to the textbox. To call this function after each click on checkbox set After Update property of all checkboxes to =MyFunctionToUpdateTextbox instead of [Event Procedure]
Private Function MyFunctionToUpdateTextbox()
Dim strText As String
If Me.cb1 = True Then
strText = strText & "INACTIVO;"
End If
If Me.cb2 = True Then
strText = strText & "DISCREPANCIA;"
End If
If Me.cb3 = True Then
strText = strText & "Text for cb3"
End If
Me.txtComentarios = strText
End Function

Related

Hide a Form tab depending on the value of a field

pretty simple question here in scope.
Question:
Wondering If I would be able to hide the tabs of a form based off the values of a table's fields.
I have been reading the 2019 Access Bible and so far it is still unclear to me how I would write the VBA module to constantly be running. Im asking the question a little early in my attempts, but hoping I can ask this well enough to get a head start.
I dont quite understand the execution model of VBA for access yet. I have prior expierence coding but this will be my 1st time in access. Just looking for a little help on how to write the function scope. You see below that I think it should be "Main" something, as I want it to run whenever in form view. Like I know how to write Private sub functions to respond to a button click. But not for a function that just runs in the background of the form.
I guess the real question is when to execute? Right? Any suggestions?
I was thinking something along the line of this below.
Main function()
If Me.FieldProcess_Water = "1" Then
Me.TabProcess_Water.Visible = True
Else
Me.TabProcess_Water.Visible = False
End If
End Sub
This requires some setup to reduce redundant code but should do what you want.
First you'll need your checkbox names and page names to be similar. In my example I have the page names as Tab_Name and the checkboxes as just Name. eg. Tab_Process Water and Process Water.
Then Create a sub called Form_Current() in the form's code-behind.
Private Sub Form_Current()
Dim chk As Control
For Each chk In Me.Controls
If chk.ControlType = acCheckBox Then
If chk = False Then
'Change TabCtl0 to whatever your's is called
Me.TabCtl0.Pages("Tab_" & chk.Name).Visible = False
Else
Me.TabCtl0.Pages("Tab_" & chk.Name).Visible = True
End If
End If
Next
End Sub
This will iterate through the current record's checkboxes and toggle it's respective tab's visibility.
To have the CheckBox update the tabs as they are clicked:
Private Sub Form_Load()
Dim chk As Control
Dim prop As Variant
For Each chk In Me.Controls
If chk.ControlType = acCheckBox Then
chk.OnClick = "=Check_Click()"
End If
Next
End Sub
This will assign a command to each checkbox.
Dim caller As String
caller = Me.ActiveControl.Name
If Me.ActiveControl.Value = False Then
Me.TabCtl0.Pages("Tab_" & caller).Visible = False
Else
Me.TabCtl0.Pages("Tab_" & caller).Visible = True
End If
This will hide the relevant tabs.

Create dynamic input for variable

I hope someone can help, I am new to programming, my problem is this:
40 checkboxes on a form which one by one, needs to be checked for boolean "True" or "False" (checked or unchecked by user), so that I can run individual code for each "True" case.
I am trying to include a counter "i" in the "MS Access checkbox reference" which I use for the variable, to give me the value of the given checkbox. The following code should show what I try to accomplish, can anybody point me in the right direction, without using a very advanced solution? I presume it is because it cannot execute all of this in a single step or because it only sees my input for the variable as a string and not a command to execute :
Do While Flag = True
Dim CheckboxVar As Boolean
i = i + 1
If i = 40 Then
Flag = False
End If
CheckboxVar = "Me.Checkbox" & i & ".Value"
AddWhereSQL = SQLBuilder (CheckboxVar)
Loop
(Retrieve the value of Checkbox1 and send it to SQLBuilder, retrieve Checkbox2 and send it to SQLBuilder, and so on)
Loop through your checkboxes like this:
Sub Test()
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeOf ctrl Is CheckBox Then
If ctrl.Value = True Then
'do something
End If
End If
Next ctrl
End Sub
Naming your checkboxes "Checkbox1", "Checkbox2", etc. is tiresome and not the best naming practice. The code above will find every checkbox on the form but you could easily restrict it to all checkboxes with a specific tag, for example.
To loop through the controls, you can do this:
Dim i As Long
For i = 1 To 40
If Me.Controls("CheckBoxControlName" & i).Value = -1 Then
'The control value is True
End If
Next i
If you code is placed in a Standard Module, change Me to Forms!YourFormName.
I think you need a "for" loop. Maybe something like:
CheckboxVar = " WHERE "
For i = 1 to 40
CheckboxVar = Me.Controls("Checkbox" & i).Value = True & " AND " & checkboxVar
next

Reference checkbox name/value in a subroutine

Is there a way to pass a checkbox value from a userform? I've seen it done when the checkbox is on the worksheet but I haven't been able to get it to work when it comes from my userform.
I have several repeating if statements and the only difference between them is the name of the checkbox. I'm sure there's a simple fix that I just haven't found yet. Any help is appreciated.
Edit: included code
If LockboxCheckBox.Value = True Then
If IsEmpty(wsInput.Cells(emptyRow, productCol)) Then
wsInput.Cells(emptyRow, productCol).Value = LockboxCheckBox.Caption
Else: wsInput.Cells(emptyRow, productCol).Value = wsInput.Cells(emptyRow, productCol).Value & ", " & LockboxCheckBox.Caption
End If
End If
I want to make this a small subroutine and need to pass the checkbox.value as well as the checkbox.caption to it when I call it.
The following code example demonstrates how to pass a Checkbox control on a UserForm to another procedure, get the checkbox's value and caption, and do something with them.
Note that I choose to pass the checkbox, rather than the value and caption as two parameters, as this will reduce the amount of code you need to type.
Private Sub btnOK_Click()
Dim chk As MSForms.CheckBox
Set chk = Me.CheckBox1
ProcessCheckBox chk
ProcessCheckBox Me.CheckBox2
End Sub
Sub ProcessCheckBox(chk As MSForms.CheckBox)
Dim chkVal As Boolean
Dim chkCap As String
chkVal = chk.value
chkCap = chk.Caption
If chkVal = True Then
Debug.Print chkCap & " is true"
Else
Debug.Print chkCap & " is false"
End If
End Sub

Using a swear word filter with InStr in Visual Basic 2012

I want to compare the IF argument to a string array. The user will try to put in a teamname into a textbox, if the user uses a swear word anywhere within that textbox, it will display an error message and clear the textbox. If the user has not sworn, it will register the teamname and carry on with the program (As can be seen in the 2nd IF statement). I have tried to get this code to work for a week now and cannot get it to work.
Private Sub SelectionButtonEnter_Click(sender As Object, e As EventArgs) Handles SelectionButtonEnter.Click
Dim HasSworn As Boolean = False
Dim swears() As String = {"Fuck", "fuck", "Shit", "shit", "Shite", "shite", "Dick", "dick", "Pussy", "pussy", "Piss", "piss", "Vagina", "vagina", "Faggot", "faggot"} 'Declare potential swear words the kids can use
For Each swear As String In swears
If InStr(SelectionTextBoxTeamName.Text, swear) > 0 Then
SelectionTextBoxTeamName.Clear() 'Clear the textbox
MessageBox.Show("Remember ... You can be disqualified, raise your hand and Blair will set up the program for you again") 'Let the user know they have entered a swear word and ask them to select another team name
End If
If Not InStr(SelectionTextBoxTeamName.Text, swear) > 0 Then
Timer1.Enabled = True 'Enable timer 1 for the learn box
Timer3ForSelection.Enabled = True 'Enable this timer to show the learn button
TeamName = SelectionTextBoxTeamName.Text() 'Once this button has been pressed, store the content of that textbox in a the TeamName string
SelectionLabelTeamName.Text = "Welcome " & SelectionTextBoxTeamName.Text & " Please click 'Learn' in the box below to begin" 'Display the contents of the string along with other text here
SelectionLabelTeamNameTL.Text() = "Team Name: " & TeamName 'Display the contents of the string along with other text here
SelectionTextBoxTeamName.BackColor = Color.Green 'Have the back color of the box set to green
SelectionTextBoxTeamName.Enabled = False 'Do not allow the user/users enter another team name
End If
Next 'A next must be declared in a for each statement
End Sub
Thanks in advance.
I don't think I'd approach it that way; if the user types f**kyou, your code wouldn't catch it. How about this instead:
In your code:
If ContainsBannedWord(SelectionTextBoxTeamName.Text) Then
Msgbox "Hold out your hand, bad person. SlapSlapSlap"
Else
Msgbox "Good boy!"
End if
Function ContainsBannedWord(sInput As String) As Boolean
Dim aBannedWords(1 To 5) As String
Dim x As Long
' Make all the banned words capitalized
aBannedWords(1) = "BANNED1"
aBannedWords(2) = "BANNED2"
aBannedWords(3) = "BANNED3"
aBannedWords(4) = "BANNED4"
aBannedWords(5) = "BANNED5"
For x = LBound(aBannedWords) To UBound(aBannedWords)
If InStr(UCase(sInput), aBannedWords(x)) > 0 Then
ContainsBannedWord = True
Exit Function
End If
Next
ContainsBannedWord = False
End Function

VBA Userform with Textbox - formatting the text

so I'm very new to VBA. I've created a very simple template that when opened, gives me a form to fill out which will insert text into a document through a commandbutton.
I'm trying to take it a step further a bit but am not sure how to go about bringing the code together. To insert the text, I'm using the bookmark feature. On my form, I have 4 Textboxes that act as options. If all 4 are filled in, the text looks like:
Option1Option2Option3Option4
I need it to look like:
Option1, Option2, Option3 and Option4
Not only that but I would like it so that the "and" is added depending on how many textboxes are filled in. For example, if I only have the first two filled it, I need it to look like:
Option1 and Option2
Does that make sense? Below is how it's structured currently. I would appreciate any pointers in moving forward.
Private Sub cmdSubmit_Click()
Application.ScreenUpdating = False
With ActiveDocument
.Bookmarks("Program1").Range.Text = TextBox1.Value
.Bookmarks("Program2").Range.Text = TextBox2.Value
.Bookmarks("Program3").Range.Text = TextBox3.Value
.Bookmarks("program4").Range.Text = TextBox4.Value
End With
Application.ScreenUpdating = True
Unload Me
End Sub
If these bookmarks are contiguous, there is no need for four bookmarks. Add the following module-level variables:
Private s As String, hasAnd As Boolean
Create a Sub which prepends the text of a textbox to the private variable, inserting a comma or and as appropriate:
Private Sub AppendText(txt As TextBox)
If Len(txt.Text) = 0 Then Exit Sub
If Len(s) = 0 Then
s = txt.Text
ElseIf Not hasAnd Then
hasAnd = True
s = txt.Text & " and " & s
Else
s = txt.Text & ", " & s
End If
End Sub
Call the subprocedure for each textbox in reverse order:
AppendText TextBox4
AppendText TextBox3
AppendText TextBox2
AppendText TextBox1
Then, use the value of s as the text of the bookmark:
ActiveDocument.Bookmarks("Program1").Range.Text = s