How to use this VBA code to use as Public Subroutine in Access VBA - vba

I have got this code below that restricts users to leave an empty field in a form. Now I want to use this in all of my forms. I've tried to use in Public Subroutine using a module. But it doesn't work.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim msg As String, Style As Integer, Title As String
Dim nl As String, ctl As Control
nl = vbNewLine & vbNewLine
For Each ctl In Me.Controls
If ctl.ControlType = acTextBox Then
If ctl.Tag = "*" And Trim(ctl & "") = "" Then
msg = "Data Required for '" & ctl.Name & "' field!" & nl & _
"You can't save this record until this data is provided!" & nl & _
"Enter the data and try again . . . "
Style = vbCritical + vbOKOnly
Title = "Required Data..."
MsgBox msg, Style, Title
ctl.SetFocus
Cancel = True
Exit For
End If
End If
Next
End Sub
I just want to use this in all of my forms. How do I accomplish this?

Good question, and good idea.
So, keep in mind that "me" is just the current form you are working with.
So, create a plane jane standard code module. And drop in your function like this with a "few" changes.
Public Function CheckRequired(MyMe As Form) As Boolean
Dim msg As String
Dim Style As Integer
Dim Title As String
Dim nl As String
Dim ctl As Control
nl = vbCrLf ' crlf gives you one line
CheckRequired = False ' assume everything ok
For Each ctl In MyMe.Controls
If ctl.ControlType = acTextBox Then
If ctl.Tag = "*" And Trim(ctl & "") = "" Then
msg = "Data Required for '" & ctl.Name & "' field!" & nl & _
"You can't save this record until this data is provided!" & nl & _
"Enter the data and try again . . . "
Style = vbCritical + vbOKOnly
Title = "Required Data..."
MsgBox msg, Style, Title
ctl.SetFocus
CheckRequired = True
Exit Function
End If
End If
Next
End Function
Now, in the forms event (which has that cancel), then you do this:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = CheckRequired(Me)
End Sub

As #June7 mentioned, Me is only valid behind forms and reports. It is shorthand alias for the form/report name/object. To achieve what you are looking for, you can try this concept. Create the global routine like below :
Public Function Validate_BeforeUpdate(frm As Form) As Integer
Dim msg As String, Style As Integer, Title As String
Dim nl As String, ctl As Control
nl = vbNewLine & vbNewLine
For Each ctl In frm.Controls
'''' your other code
Validate_BeforeUpdate = 1
Exit For
Next
End Sub
And to use this from your other forms, do it like below :
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Validate_BeforeUpdate(Me) = 1 Then
Cancel = True
End If
End Sub
This is not a tested code, if you follow this idea, you should be okay to have what you are trying to do.

Related

Save reports according to choice from a sub form

I have a main form called (frmcarSearch) that displays table data called (tblCar).
The form contains three drop-down menu (cmbCar, cmbType, cmbGroup) that allow user to filter data and display them in a sub-form called (frmCarSub)
and there are three buttons to save the filtered data btnPrint, btnPDF, btnExcel.
The question is: How to write a code for each button so that the report displays (or save) the data in the sub-form according to the choice from each drop-down menu?
The code for each combo box:
Private Sub cmbCar_AfterUpdate()
Me.cmbGroup.Value = ""
Me.cmbType.Value = ""
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = "[CarNum]= '" & [cmbCar] & "'"
Me.frmCarSub.Form.FilterOn = True
End Sub
Private Sub cmbType_AfterUpdate()
Me.cmbGroup.Value = ""
Me.cmbCar.Value = ""
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = "[TypeName]='" & [cmbType] & "'"
Me.frmCarSub.Form.FilterOn = True
End Sub
Private Sub cmbGroup_AfterUpdate()
Me.cmbCar.Value = ""
Me.cmbType.Value = ""
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = "[CarGroupName]= '" & [cmbGroup] & "'"
Me.frmCarSub.Form.FilterOn = True
End Sub
I used this code for btnPrint button
Private Sub btnPrint_Click()
If IsNull([cmbCar]) Then
DoCmd.OpenReport "rptCar", acViewPreview
Else
DoCmd.OpenReport "rptCar", acViewPreview, , "[CarNum]='" & [cmbCar] & "'"
End If
End Sub
But the problem with this code is that I have to use three buttons for the three menus and this is illogical.
Thank you.
You could define a function such as the following with the module for your form:
Function FilterString() As String
If Not IsNull(cmbCar) Then FilterString = " AND [CarNum]= '" & cmbCar & "'"
If Not IsNull(cmbType) Then FilterString = FilterString & " AND [TypeName]= '" & cmbType & "'"
If Not IsNull(cmbGroup) Then FilterString = FilterString & " AND [CarGroupName]= '" & cmbGroup & "'"
FilterString = Mid(FilterString, 6)
End Function
Then, define another function such as:
Function SetFilter()
Me.frmCarSub.SetFocus
Me.frmCarSub.Form.Filter = FilterString
Me.frmCarSub.Form.FilterOn = True
End Function
Then, the event handlers for each of your comboboxes become:
Private Sub cmbCar_AfterUpdate()
SetFilter
End Sub
Private Sub cmbType_AfterUpdate()
SetFilter
End Sub
Private Sub cmbGroup_AfterUpdate()
SetFilter
End Sub
Finally, the Print button event handler can become:
Private Sub btnPrint_Click()
If FilterString = vbNullString Then
DoCmd.OpenReport "rptCar", acViewPreview
Else
DoCmd.OpenReport "rptCar", acViewPreview, , FilterString
End If
End Sub
And the user also has the ability to filter by more than one field.

Display selected radio button and check box on a msgbox when button1 is clicked VB

So what I'm trying to do is create a MessageBox when Button1 is clicked with the selected Radiobuttons and Checkboxes on it.
Here's the design:
And I want the output to be something like this:
Thank you
Better way of doing this is to loop through the groupbox controls and check if the checkboxes are checked and if yes append that to some string.And after all your checks are complete display the string using messagebox.Simple as it is.To provide some more light to the solutions please go through the below code
Looping through controls
Dim strfinal As String
For Each gb As Control In Me.Controls
If gb.GetType() Is GetType(GroupBox) Then
Dim str As String
str = gb.Text
For Each c As CheckBox In gb.Controls
If c.Checked = True Then
str = str + vbNewLine + c.Text
End If
Next
If str <> "" Then
strfinal = strfinal + vbNewLine + str
End If
End If
Next
and displaying in messagebox
If strfinal <> "" Then
MessageBox.Show(strfinal, "somecaption", MessageBoxButtons.OK)
End If
hope this helps.
This code is going to give you the result exactly as in picture2 above :
Dim Toppings As String = "Toppings:" & VbCrlf
Dim TSize As String = "Size:"
Dim CrustType As String = "Crust Type:"
Here when you press on Button1, when the name of the groubBox that contains the toppings is ' ToppingsGroupBox' and the same for the other groupBoxes:
For Each CB As CheckBox In ToppingsGroupBox.Controls
If CB.Checked Then
Toppings &= "-" & CB.Text & VbCrlf
End If
End Each
For Each RB As RadioButton In SizesGroupBox.Controls
If RB.Checked Then
TSize &= RB.Text
End If
End Each
For Each RB As RadioButton In CurstTypeGroupBox.Controls
If RB.Checked Then
CurstType &= RB.Text
End If
End Each
If DineInRadioBox.Checked Then
MsgBox(TSize & VbCrlf & CurstType & Toppings & "*Dine In")
Else
MsgBox(TSize & VbCrlf & CurstType & Toppings & "*Take Out")
End If
Hope that will help you :)

Access SubForm selection depends on Combo box

I would like to Filter my sub form based on my Combo box filter. I'm getting code error. I need help with this.
After Update I have written one event:
Private Sub cboSelected_AfterUpdate()
Dim MyName As String
MyName = " select * from [ITP_Checklist Log] where ([ITP_Checklist Log].[Name] = " & Me.cboSelected & " )"
Me.ITP_Checklist_Log_subform.Form.RecordSource = MyName
Me.ITP_Checklist_Log_subform.Form.Requery
End Sub
Error:
Run-time error '3464'
Data Type Mismatch in Criteria expression.
Use quotes for string values - and Requery is only needed if you don't change the recordsource:
Private Sub cboSelected_AfterUpdate()
Dim MyName As String
MyName = "select * from [ITP_Checklist Log] where ([ITP_Checklist Log].[Name] = '" & Me!cboSelected.Value & "')"
Debug.Print MyName
If Me!ITP_Checklist_Log_subform.Form.RecordSource = MyName Then
Me!ITP_Checklist_Log_subform.Form.Requery
Else
Me!ITP_Checklist_Log_subform.Form.RecordSource = MyName
End If
End Sub

VB.Net Regex Help

I've got 3 or 4 patterns that I'm comparing user input against and I need to figure out if the user input matches one of the patters and to return the match if it does.
Since the input is multiline, I'm passing each individual line like so:
Dim strRawInput() As String = Split(txtInput.Text, vbCrLf)
Dim strInput As String
txtOutput.Text = ""
For Each strInput In strRawInput
strInput.Trim(vbCr, vbLf, Chr(32))
Validation(strInput)
Next
Then I have this to find matches:
Dim m As Match
For i = 0 To strValidator.Length - 1
Dim r As New Regex(strValidator(i))
m = r.Match(strInput)
If m.Success Then
txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
Exit Sub
Else
End If
Next
txtOutput.Text = txtOutput.Text & "Not this time" & vbCrLf
How can I do this more efficiently? Also, I added the Exit Sub there to avoid showing the "Not this time" message even after a match is found (if the match is with one of the later patterns in the array), but I'd like to find a better way of doing that too.
Thanks in advance.
Rather than generating your Regexs in the loop, generate them one time at the startup of the application. So maybe something like:
Private Shared m_regexes As New List(Of Regex)
Shared Sub New()
For Each v As String In strValidator
m_regexes.Add(New Regex(v))
Next
End Sub
And then you can change your other code to:
For Each r As Regex In m_regexes
Dim m As Match = r.Match(strInput)
If m.Success Then
txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
Exit Sub
Else
End If
Next
Regarding the Exit Sub, I think it's fine, You've discovered that it matches at least one pattern, so why continue to evaluate the rest. But if you don't like methods that can "return" in multiple places, you could just replace it with a Boolean and a Exit For as:
Dim found as Boolean = false
For Each ...
If IsMatch Then
found = True
Exit For
End If
Next
If Found Then
....
Else
.....
End If
Hmm if that's the case then wouldn't this be even better?
For i = 0 To strValidator.Length - 1
Dim r As New Regex(strValidator(i))
Dim m As Match = r.Match(strInput)
If m.Success Then
txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
Exit Sub
End If
Next

Is there any tool to convert multiline text for Visual Studio 2008/2005?

Is there any tool that will convert a multiline text, to a compatible multiline string for Visual Studio 2008/2005?
For example:
line1
line2
line3
line4
Should become:
"line1" & _
"line2" & _
"line3" & _
"line4"
This kind of tool definitely falls in the do-it-yourself category. Start a new Windows Forms application. Paste the code shown below. Put a shortcut to the program on your desktop. To use it, drag a file from Explorer onto the form. Switch to Visual Studio and type Ctrl+V.
Public Class Form1
Public Sub New()
InitializeComponent()
Me.AllowDrop = True
End Sub
Protected Overrides Sub OnDragEnter(ByVal e As DragEventArgs)
If e.Data.GetDataPresent("FileDrop") Then e.Effect = DragDropEffects.Copy
End Sub
Protected Overrides Sub OnDragDrop(ByVal e As DragEventArgs)
Dim files = DirectCast(e.Data.GetData("FileDrop", False), String())
Dim txt As New System.Text.StringBuilder
Dim lines = System.IO.File.ReadAllLines(files(0))
For ix As Integer = 0 To lines.Length - 1
txt.Append("""" + lines(ix).Replace("""", """""") + """")
If ix < lines.Length - 1 Then txt.AppendLine(" & _")
Next
Clipboard.SetText(txt.ToString())
End Sub
End Class
The better mousetrap is to add the file as a resource instead of hard-coding the text.
Is this what you're looking for?
Dim testString As String = "line1" & vbCrLf & _
"line2" & vbCrLf & _
"line3" & vbCrLf & _
"line4"
Dim allLines() As String = Microsoft.VisualBasic.Strings.Split(testString, vbCrLf)
Dim strConverter As New System.Text.StringBuilder
For Each line As String In allLines
strConverter.Append("""" & line & """").Append(" & _").Append(vbCrLf)
Next
If allLines.Length > 0 Then strConverter.Length -= (" & _" & vbCrLf).Length
Dim convertedString As String = strConverter.ToString
A VS Macro for Pasting Long Text as String seems like perfect solution.