I have a small data warehouse I've built in MS Access 2016. I load new data in the warehouse every month, and I want to dynamically show users of the data warehouse the date range available for reports.
I created a label that says the following: "*Data loaded for January 1, 2016 through the end of".
Next, I created a textbox named txtMaxDate. I gave the textbox a transparent border and a font that matches the label above. I placed the textbox right after the label.
In the onLoad event of the form, I wrote the following code:
Private Sub Form_Load()
Dim sql As String
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim maxLoadDate As Date
Dim theYear As String
Dim theMonth As String
Set db = CurrentDb
sql = "SELECT MAX(PayYearMonth) as MaxDate FROM tblPaySummary"
Set rs = db.OpenRecordset(sql)
rs.MoveFirst
maxLoadDate = rs!MaxDate
theYear = year(maxLoadDate)
theMonth = MonthName(month(maxLoadDate))
Me.txtMaxDate.Value = theMonth & " " & theYear
End Sub
The code gets the most recent date from the database and displays the date in the text box.
Tuesday, February 14, 2017
Thursday, April 16, 2015
VBA Function to Remove Non-Alphanumeric Characters
Occasionally, you'll run into data that has been entered with inadvertent carriage returns or other non-alphanumeric characters. Sometimes, these invisible characters can cause mysterious errors in your code. The solution is to use a function to remove any superfluous characters from the data.
The following function removes everything except for the characters indicated between the brackets. You can tweak the accepted character set as needed. The function works by looping through each character in the string and testing each character to see if it matches one of the characters listed between the square brackets.
Function cleanText(strText As String) As String
Dim valid as String
Dim test As String
valid = ""
test = ""
For i = 1 To Len(strText)
test = Mid(strText, i, 1)
'Only allow characters and spaces, not carriage returns or any other code
If test Like "[A-Z,a-z,0-9, ,.,/,~,@,#,$,%,^,&,*,(,),_,-,+,= ]" Then
valid = valid & test
End If
Next i
'Return the valid characters
cleanText = valid
End Function
The cleanText function uses the Visual Basic (VBA) "Like" operator. The Like operator is similar to using Regular Expressions and also has some similarities to the SQL Like operator. You can read more about the VBA Like operator on this page.
The following function removes everything except for the characters indicated between the brackets. You can tweak the accepted character set as needed. The function works by looping through each character in the string and testing each character to see if it matches one of the characters listed between the square brackets.
Function cleanText(strText As String) As String
Dim valid as String
Dim test As String
valid = ""
test = ""
For i = 1 To Len(strText)
test = Mid(strText, i, 1)
'Only allow characters and spaces, not carriage returns or any other code
If test Like "[A-Z,a-z,0-9, ,.,/,~,@,#,$,%,^,&,*,(,),_,-,+,= ]" Then
valid = valid & test
End If
Next i
'Return the valid characters
cleanText = valid
End Function
The cleanText function uses the Visual Basic (VBA) "Like" operator. The Like operator is similar to using Regular Expressions and also has some similarities to the SQL Like operator. You can read more about the VBA Like operator on this page.
VBA Regular Expression Phone Number Validator
This phone number validator validates numbers with or without dashes and with or without dots between the segments.
Public Function validatePhoneNo(phoneno As String) As Boolean
If phoneno <> "" Then
Dim re As RegExp
Dim matches As MatchCollection
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
re.Pattern = "^\(?\d{3}-?\.?\)?\s?\d{3}-?\.?\d{4}$"
Set matches = re.Execute(phoneno)
If matches.Count <> 1 Then
validatePhoneNo = False
Exit Function
End If
Else
validatePhoneNo = False
Exit Function
End If
validatePhoneNo = True
End Function
Public Function validatePhoneNo(phoneno As String) As Boolean
If phoneno <> "" Then
Dim re As RegExp
Dim matches As MatchCollection
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
re.Pattern = "^\(?\d{3}-?\.?\)?\s?\d{3}-?\.?\d{4}$"
Set matches = re.Execute(phoneno)
If matches.Count <> 1 Then
validatePhoneNo = False
Exit Function
End If
Else
validatePhoneNo = False
Exit Function
End If
validatePhoneNo = True
End Function
Use VBA to Automatically Set Dates in Form Fields
In this case, I have a report that requires a Begin Date and an End Date.
To make things easier for the user, I pre-fill the date fields with the date range most commonly used in the report. I use the Form_Load() event to automatically set the dates in the form fields.
Private Sub Form_Load()
Me.txtBegDt.Value = "1/1/" & Year(Date)
Me.txtEndDt.Value = Date
End Sub
The first line sets the Begin Date (txtBegDt) field to January 1 of the current year. The second line sets the End Date (txtEndDt) to the current date. Easy as that!
To make things easier for the user, I pre-fill the date fields with the date range most commonly used in the report. I use the Form_Load() event to automatically set the dates in the form fields.
Private Sub Form_Load()
Me.txtBegDt.Value = "1/1/" & Year(Date)
Me.txtEndDt.Value = Date
End Sub
The first line sets the Begin Date (txtBegDt) field to January 1 of the current year. The second line sets the End Date (txtEndDt) to the current date. Easy as that!
Shortcut to Open the VBA Editor
Using keyboard shortcuts saves a lot of time for things you do frequently. I use this shortcut every time I need to open the VBA editor in an Office Program:
Alt + F11
That's it. Practice using this shortcut a few times until it becomes second nature.
Alt + F11
That's it. Practice using this shortcut a few times until it becomes second nature.
Wednesday, May 21, 2014
Use Query Definitions to Create Dynamic Queries and Reports
The Begin and End dates in this query come from text boxes formatted as dates. The client list comes from a multi-select list box. The "qClaims" query is associated with the Claims Report. The query definition is fed a dynamic SQL statement built from the values selected by the user. The query definition makes it easy to generate a report from a dynamic query.
If Nz(Me.txtBegDt.Value, "") = "" Then
MsgBox "Please select a begin date."
Exit Sub
End If
If Nz(Me.txtEndDt.Value, "") = "" Then
MsgBox "Please select an end date."
Exit Sub
End If
DoCmd.Close acQuery, "qClaims", acSaveNo
DoCmd.Close acReport, "Claims Report"
Dim strList as String
Dim strsql As String
Dim strsql As String
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("qClaims")
strList = ""
If Me.lstClients.ItemsSelected.Count > 0 Then
For Each client In Me.lstClients.ItemsSelected
strList = strList & "'" & Me.lstClients.ItemData(client) & "',"
Next client
strList = CStr(Trim(Left(strList, Len(strList) - 1))) ' Remove trailing comma
strList = " AND i.client_id IN (" & strList & ")"
Else
strList = ""
End If
strsql = "SELECT i.client_id, i.client_name, i.fname, i.lname, i.ssn," _
& " i.sep_reason, c.charge_qu, c.charge_yr, c.charge_amount" _
& " i.sep_reason, c.charge_qu, c.charge_yr, c.charge_amount" _
& " FROM tCharges c RIGHT JOIN tSeparation_Info i ON c.sep_ID = i.id" _
& " WHERE i.mail_date BETWEEN #" & [Forms]![Claims Report]![txtBegDt] _
& "# And #" & [Forms]![Claims Report]![txtEndDt] & "# " & strList _
& " ORDER BY i.client_name"
qdf.sql = strsql ' Set the sql of the query definition
DoCmd.OpenReport "Claims Report", acViewReport
Set db = Nothing
Set qdf = Nothing
Monday, February 3, 2014
Dynamic SQL statements
Dynamic SQL statements are great when you want to give end users maximum flexibility in creating their own reports. To build dynamic SQL statements, first declare variables for each clause of a SQL statement. Here we have variables for the SELECT, FROM, WHERE, and GROUP BY clauses. The allSQL variable will hold the completed SQL statement.
Dim selSQL As String
Dim fromSQL As String
Dim whereSQL As String
Dim groupSQL As String
Dim allSQL As String
Dim func As String
Next, we create a query definition object that will be used to run the dynamic SQL statement. "CustomReport" is a query I created in the visual query builder. It's just a container that will ultimately be used to run the dynamic SQL statement.
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
Set db = CurrentDb
Set qdf = db.QueryDefs("CustomReport")
Next, initialize the SQL query strings.
selSQL = "SELECT m.PayYear"
fromSQL = " FROM client_list c INNER JOIN metrics m ON c.apexID = m.apexID"
groupSQL = " GROUP BY m.PayYear"
whereSQL = " WHERE 1=1"
Next, we will build the SELECT and GROUP BY portions of the SQL statement from values selected on a form:
In this case, we will Sum the Admin Fees and Gross Pay amounts and group those amounts by Salesforce Client, Quarter, and Salesforce Industry. We will be creating our report from a mini data warehouse we've built from data exported out of Salesforce.com and from another system called Summit Apex.
The following statements iterate through the different Display Value fields to retrieve the selected values and apply them to the SQL sections. Notice how the aggregate function is set in a variable called "func." If the user chooses "none" from the Aggregate Function radio group, then we will simply set the groupSQL string equal to "" near the end of the subprocedure.
' Time Detail Level
If Me.optTime.Value = 1 Then
selSQL = selSQL & ", m.PayMonth"
groupSQL = groupSQL & ", m.PayMonth"
ElseIf Me.optTime.Value = 2 Then
selSQL = selSQL & ", m.quarter"
groupSQL = groupSQL & ", m.quarter"
End If
' Client Level
If Me.optClLevel.Value = 1 Then
selSQL = selSQL & ", c.ApexID, c.ApexName"
groupSQL = groupSQL & ", c.ApexID, c.ApexName"
ElseIf Me.optClLevel.Value = 2 Then
selSQL = selSQL & ", c.ApexSFIDCaseSens, c.SalesforceName"
groupSQL = groupSQL & ", c.ApexSFIDCaseSens, c.SalesforceName"
End If
' Aggregate Function
If Me.optFunc.Value = 1 Then
func = "SUM"
ElseIf Me.optFunc.Value = 2 Then
func = "AVG"
ElseIf Me.optFunc.Value = 3 Then
func = "MAX"
ElseIf Me.optFunc.Value = 4 Then
func = "MIN"
ElseIf Me.optFunc.Value = 5 Then
func = ""
End If
' Metrics
For Each indx In Me.lstMetrics.ItemsSelected
If func = "" Then
selSQL = selSQL & ", m." & Me.lstMetrics.ItemData(indx)
Else
If func <> "SUM" Then
selSQL = selSQL & ", " & func & "(m." & Me.lstMetrics.ItemData(indx) & ") as " & Me.lstMetrics.ItemData(indx) & func & "PerMonth"
Else
selSQL = selSQL & ", " & func & "(m." & Me.lstMetrics.ItemData(indx) & ") as " & Me.lstMetrics.ItemData(indx) & "_" & func
End If
End If
Next indx
' Attributes
For Each indx In Me.lstAttr.ItemsSelected
selSQL = selSQL & ", c." & Me.lstAttr.ItemData(indx)
groupSQL = groupSQL & ", c." & Me.lstAttr.ItemData(indx)
Next indx
Next, we choose from a set of Attribute Filters to start building the WHERE clause.
In this case, we are limiting the results to the year 2013 and to the state of Utah. Here's the code to handle all of the Attribute filters:
' Date Range
If Nz(Me.txtBegDt.Value, "") <> "" And Nz(Me.txtEndDt.Value, "") <> "" Then
whereSQL = whereSQL & " AND m.MonthEndDate BETWEEN #" & Me.txtBegDt.Value & "# AND #" & Me.txtEndDt.Value & "#"
End If
'Company Number
If Nz(Me.txtCoNum.Value, "") <> "" Then
whereSQL = whereSQL & " AND c.ApexCompany = '" & Me.txtCoNum.Value & "'"
End If
' Industry Filter In
Dim industryList As String
industryList = ""
For Each indx In Me.lstIndustry.ItemsSelected
industryList = industryList & "'" & Me.lstIndustry.ItemData(indx) & "',"
Next indx
If industryList <> "" Then
whereSQL = whereSQL & " AND c.SFIndustry IN (" & Mid(industryList, 1, Len(industryList) - 1) & ")"
End If
' State Filter In
Dim stateList As String
stateList = ""
For Each indx In Me.lstState.ItemsSelected
stateList = stateList & "'" & Me.lstState.ItemData(indx) & "',"
Next indx
If stateList <> "" Then
whereSQL = whereSQL & " AND c.State IN (" & Mid(stateList, 1, Len(stateList) - 1) & ")"
End If
' City Filter In
Dim cityList As String
cityList = ""
For Each indx In Me.lstCity.ItemsSelected
cityList = cityList & "'" & Me.lstCity.ItemData(indx) & "',"
Next indx
If cityList <> "" Then
whereSQL = whereSQL & " AND c.city IN (" & Mid(cityList, 1, Len(cityList) - 1) & ")"
End If
' Zip Filter In
Dim zipList As String
zipList = ""
For Each indx In Me.lstZip.ItemsSelected
zipList = zipList & "'" & Me.lstZip.ItemData(indx) & "',"
Next indx
If zipList <> "" Then
whereSQL = whereSQL & " AND c.zip IN (" & Mid(zipList, 1, Len(zipList) - 1) & ")"
End If
' Apex Client Filter In
Dim apexClList As String
apexClList = ""
For Each indx In Me.lstApexClients.ItemsSelected
apexClList = apexClList & "'" & Me.lstApexClients.ItemData(indx) & "',"
Next indx
If apexClList <> "" Then
whereSQL = whereSQL & " AND c.ApexID IN (" & Mid(apexClList, 1, Len(apexClList) - 1) & ")"
End If
' Salesforce Client Filter In
Dim sfClList As String
sfClList = ""
For Each indx In Me.lstSFClients.ItemsSelected
sfClList = sfClList & "'" & Me.lstSFClients.ItemData(indx) & "',"
Next indx
If sfClList <> "" Then
whereSQL = whereSQL & " AND c.ApexSFIDCaseSens IN (" & Mid(sfClList, 1, Len(sfClList) - 1) & ")"
End If
By breaking the SQL statement down into its component parts, we can easily add additional filters and attributes to the form to give the end user maximum flexibility in building their own custom reports.
The following code concatenates each SQL section together to create the final statement:
allSQL = selSQL & fromSQL & whereSQL & groupSQL
I used debug.print to print the allSQL variable to the Immediate window in the VBA editor. Here's what the final SQL statement looks like:
SELECT m.PayYear, m.quarter, c.ApexSFIDCaseSens, c.SalesforceName, SUM(m.AdminFees) as AdminFees_SUM, SUM(m.GrossPay) as GrossPay_SUM, c.SFIndustry
FROM client_list c INNER JOIN metrics m ON c.apexID = m.apexID
WHERE 1=1 AND m.MonthEndDate BETWEEN #1/1/2013# AND #12/31/2013# AND c.State IN ('UT') GROUP BY m.PayYear, m.quarter, c.ApexSFIDCaseSens, c.SalesforceName, c.SFIndustry
In order to run the SQL statement and show the report, we feed the SQL statement to the Query Definition object:
qdf.SQL = allSQL
Finally, we open the report and display the output:
DoCmd.OpenQuery "CustomReport", acViewNormal
We could just as easily export the report to Excel as follows:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "CustomReport", curPath & "\Excel Exports\CustomReport.xlsx"
Dim selSQL As String
Dim fromSQL As String
Dim whereSQL As String
Dim groupSQL As String
Dim allSQL As String
Dim func As String
Next, we create a query definition object that will be used to run the dynamic SQL statement. "CustomReport" is a query I created in the visual query builder. It's just a container that will ultimately be used to run the dynamic SQL statement.
Dim qdf As DAO.QueryDef
Dim db As DAO.Database
Set db = CurrentDb
Set qdf = db.QueryDefs("CustomReport")
Next, initialize the SQL query strings.
selSQL = "SELECT m.PayYear"
fromSQL = " FROM client_list c INNER JOIN metrics m ON c.apexID = m.apexID"
groupSQL = " GROUP BY m.PayYear"
whereSQL = " WHERE 1=1"
Next, we will build the SELECT and GROUP BY portions of the SQL statement from values selected on a form:
In this case, we will Sum the Admin Fees and Gross Pay amounts and group those amounts by Salesforce Client, Quarter, and Salesforce Industry. We will be creating our report from a mini data warehouse we've built from data exported out of Salesforce.com and from another system called Summit Apex.
The following statements iterate through the different Display Value fields to retrieve the selected values and apply them to the SQL sections. Notice how the aggregate function is set in a variable called "func." If the user chooses "none" from the Aggregate Function radio group, then we will simply set the groupSQL string equal to "" near the end of the subprocedure.
' Time Detail Level
If Me.optTime.Value = 1 Then
selSQL = selSQL & ", m.PayMonth"
groupSQL = groupSQL & ", m.PayMonth"
ElseIf Me.optTime.Value = 2 Then
selSQL = selSQL & ", m.quarter"
groupSQL = groupSQL & ", m.quarter"
End If
' Client Level
If Me.optClLevel.Value = 1 Then
selSQL = selSQL & ", c.ApexID, c.ApexName"
groupSQL = groupSQL & ", c.ApexID, c.ApexName"
ElseIf Me.optClLevel.Value = 2 Then
selSQL = selSQL & ", c.ApexSFIDCaseSens, c.SalesforceName"
groupSQL = groupSQL & ", c.ApexSFIDCaseSens, c.SalesforceName"
End If
' Aggregate Function
If Me.optFunc.Value = 1 Then
func = "SUM"
ElseIf Me.optFunc.Value = 2 Then
func = "AVG"
ElseIf Me.optFunc.Value = 3 Then
func = "MAX"
ElseIf Me.optFunc.Value = 4 Then
func = "MIN"
ElseIf Me.optFunc.Value = 5 Then
func = ""
End If
' Metrics
For Each indx In Me.lstMetrics.ItemsSelected
If func = "" Then
selSQL = selSQL & ", m." & Me.lstMetrics.ItemData(indx)
Else
If func <> "SUM" Then
selSQL = selSQL & ", " & func & "(m." & Me.lstMetrics.ItemData(indx) & ") as " & Me.lstMetrics.ItemData(indx) & func & "PerMonth"
Else
selSQL = selSQL & ", " & func & "(m." & Me.lstMetrics.ItemData(indx) & ") as " & Me.lstMetrics.ItemData(indx) & "_" & func
End If
End If
Next indx
' Attributes
For Each indx In Me.lstAttr.ItemsSelected
selSQL = selSQL & ", c." & Me.lstAttr.ItemData(indx)
groupSQL = groupSQL & ", c." & Me.lstAttr.ItemData(indx)
Next indx
Next, we choose from a set of Attribute Filters to start building the WHERE clause.
' Date Range
If Nz(Me.txtBegDt.Value, "") <> "" And Nz(Me.txtEndDt.Value, "") <> "" Then
whereSQL = whereSQL & " AND m.MonthEndDate BETWEEN #" & Me.txtBegDt.Value & "# AND #" & Me.txtEndDt.Value & "#"
End If
'Company Number
If Nz(Me.txtCoNum.Value, "") <> "" Then
whereSQL = whereSQL & " AND c.ApexCompany = '" & Me.txtCoNum.Value & "'"
End If
' Industry Filter In
Dim industryList As String
industryList = ""
For Each indx In Me.lstIndustry.ItemsSelected
industryList = industryList & "'" & Me.lstIndustry.ItemData(indx) & "',"
Next indx
If industryList <> "" Then
whereSQL = whereSQL & " AND c.SFIndustry IN (" & Mid(industryList, 1, Len(industryList) - 1) & ")"
End If
' State Filter In
Dim stateList As String
stateList = ""
For Each indx In Me.lstState.ItemsSelected
stateList = stateList & "'" & Me.lstState.ItemData(indx) & "',"
Next indx
If stateList <> "" Then
whereSQL = whereSQL & " AND c.State IN (" & Mid(stateList, 1, Len(stateList) - 1) & ")"
End If
' City Filter In
Dim cityList As String
cityList = ""
For Each indx In Me.lstCity.ItemsSelected
cityList = cityList & "'" & Me.lstCity.ItemData(indx) & "',"
Next indx
If cityList <> "" Then
whereSQL = whereSQL & " AND c.city IN (" & Mid(cityList, 1, Len(cityList) - 1) & ")"
End If
' Zip Filter In
Dim zipList As String
zipList = ""
For Each indx In Me.lstZip.ItemsSelected
zipList = zipList & "'" & Me.lstZip.ItemData(indx) & "',"
Next indx
If zipList <> "" Then
whereSQL = whereSQL & " AND c.zip IN (" & Mid(zipList, 1, Len(zipList) - 1) & ")"
End If
' Apex Client Filter In
Dim apexClList As String
apexClList = ""
For Each indx In Me.lstApexClients.ItemsSelected
apexClList = apexClList & "'" & Me.lstApexClients.ItemData(indx) & "',"
Next indx
If apexClList <> "" Then
whereSQL = whereSQL & " AND c.ApexID IN (" & Mid(apexClList, 1, Len(apexClList) - 1) & ")"
End If
' Salesforce Client Filter In
Dim sfClList As String
sfClList = ""
For Each indx In Me.lstSFClients.ItemsSelected
sfClList = sfClList & "'" & Me.lstSFClients.ItemData(indx) & "',"
Next indx
If sfClList <> "" Then
whereSQL = whereSQL & " AND c.ApexSFIDCaseSens IN (" & Mid(sfClList, 1, Len(sfClList) - 1) & ")"
End If
By breaking the SQL statement down into its component parts, we can easily add additional filters and attributes to the form to give the end user maximum flexibility in building their own custom reports.
The following code concatenates each SQL section together to create the final statement:
allSQL = selSQL & fromSQL & whereSQL & groupSQL
I used debug.print to print the allSQL variable to the Immediate window in the VBA editor. Here's what the final SQL statement looks like:
SELECT m.PayYear, m.quarter, c.ApexSFIDCaseSens, c.SalesforceName, SUM(m.AdminFees) as AdminFees_SUM, SUM(m.GrossPay) as GrossPay_SUM, c.SFIndustry
FROM client_list c INNER JOIN metrics m ON c.apexID = m.apexID
WHERE 1=1 AND m.MonthEndDate BETWEEN #1/1/2013# AND #12/31/2013# AND c.State IN ('UT') GROUP BY m.PayYear, m.quarter, c.ApexSFIDCaseSens, c.SalesforceName, c.SFIndustry
In order to run the SQL statement and show the report, we feed the SQL statement to the Query Definition object:
qdf.SQL = allSQL
Finally, we open the report and display the output:
DoCmd.OpenQuery "CustomReport", acViewNormal
We could just as easily export the report to Excel as follows:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "CustomReport", curPath & "\Excel Exports\CustomReport.xlsx"
Subscribe to:
Posts (Atom)
