<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener("load", function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <iframe src="http://www.blogger.com/navbar.g?targetBlogID=34083602&amp;blogName=LEARN+MS-ACCESS+TIPS+AND+TRICKS&amp;publishMode=PUBLISH_MODE_FTP&amp;navbarType=BLUE&amp;layoutType=CLASSIC&amp;searchRoot=http%3A%2F%2Fblogsearch.google.com%2F&amp;blogLocale=en_US&amp;homepageUrl=http%3A%2F%2Fwww.msaccesstips.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> <div></div>
www.msaccesstips.com

LEARN MS-ACCESS TIPS AND TRICKS


International Response Fund

LEARN MS-ACCESS TIPS AND TRICKS

↑ Grab this Headline Animator

Your Ad Here
Monday, December 14, 2009

Filter with BuildCriteria Function

Any method that helps to find data quickly on a Form is always welcome by Users. There are several options available when you are in Form View Mode.
When you Right-click on a Field a Shortcut Menu will popup showing four data filter options as shown on the sample image given below.


Form Shortcut Menu Image

The third option Filter For can accept a Criteria Expression like >10200 AND <=10300 or similar to filter a Range of Values from the selected field.

If you would like to see more options then point on Filter option in Record Menu. There you can find two new Options: Filter by Form and Advance Filter/Sort. Filter by Form allows you to set up Criteria in more than one field to select records based on Form fields.

The Advance Filter/Sort will open up Filter Design (Query Design) Window with the Source Table/Query of the Form with whatever criteria you have entered into the Filter for or Filter by Form Options earlier, if any. You can further modify the filter conditions and Sorting Order and select Apply Filter from the Records Menu to view the result.


But, if you would like to build a Custom Filter Option for the User; based on a particular Field on the Form then you can use the built-in Function BuildCriteria() and write a VBA Sub-Routine around this Function to filter the data. Run the Sub-Routine on a Button Click Event Procedure and let the User input the Filter Criteria in various ways as he likes.


The Usage of the Function is very simple. Let us try few examples of the Function directly in the Debug Window (Immediate Window) to understand how it works.

  1. Press Alt+F11 to display the Visual Basic Editing Window.

  2. Press Ctrl+G to display the Debug window.

  3. Type the following example expressions and press Enter key to display the output:



? BuildCriteria("OrderID",dblong,"10200")

Result: OrderID=10200


The BuildCriteria() Function needs three Function Parameters. OrderID is the Data Field Name, dbLong indicates that OrderID is a Numeric Field with values of Long Integer Type and the last Value 10200 is OrderID Criteria value for selecting records. The OrderID Field Name will be inserted in appropriate locations in the Criteria expression by the BuildCriteria() Function.


The last parameter value we can use in several ways depending on how we want the result. Let us see few more examples before we implement this method on a Form. Type the following expressions in the Debug Window to see how it works:


? BuildCriteria("OrderID",dblong, ">=10200 AND <10300")


Result: OrderID>=10200 And OrderID<10300


? BuildCriteria("OrderID",dblong,">=10200 AND <10300 OR >=10400 AND <10500")


Result: OrderID>=10200 And OrderID<10300 Or OrderID>=10400 And OrderID<10500


Try changing the data type to dbText, for example:


? BuildCriteria("OrderID",dbText,"10200")


Result: OrderID="10200"


? BbuildCriteria("OrderDate",dbDate,">10/15/2009 and <=10/31/2009")


Result: OrderDate>#10/15/2009# And OrderDate<=#10/31/2009#


After getting the result text from the BuildCriteria() Function all we have to do is to insert it into the Filter Property of the Form and turn ON the Filter action.


Let us design a simple Form to Run our example straight away.



  1. Import the Orders Table from C:\Program Files\Microsoft Office\Officell\Samples\Northwind.mdb sample database.

  2. Click on Orders Table to Select it and select Form from Insert Menu.

  3. Select Auto Form:Tabular to create a Form and save it with the name Orders.

  4. Open the Orders Form in Design View.

  5. Expand the Form Header Area and drag all the Field Headings down to get enough room to create a Command Button above the Field Headings.

  6. Display the ToolBox, if it is not visible (View - ->Toolbox).

  7. Select the Command Button Tool and create a Command Button on the Header of the Form.

  8. While the Command Button is still in selected state display its Property Sheet (View --> Properties).

  9. Change the Name Property Value to cmdFilter and change the Caption Property Value to OrderID Filter.

  10. Display the Code Module of the Form (View - -> Code).

  11. Copy and Paste the following VBA Code into the Module.



  12. Private Sub cmdFilter_Click()
    Dim txtCondition, txtFilter As String

    txtCondition = InputBox("OrderID Value/Range of Values")

    If Len(txtCondition) = 0 Then
    Me.FilterOn = False
    Exit Sub
    End If

    txtFilter = BuildCriteria("OrderID", dbLong, txtCondition)

    Me.FilterOn = False
    Me.Filter = txtFilter
    Me.FilterOn = True

    End Sub

  13. Save and Close the Form.

  14. You may click on the OrderID Filter Command Button and enter any of the examples (except the one with Date) criteria expressions we have entered as third Parameter into the BuildCriteria() Function above, when prompted for the Filter Condition.


If you don't like to use InputBox() to prompt for Criteria Values then you may create a Text Box on the Form where Users can enter the Criteria expression before hitting on the Command Button.

The limitation of the BuildCriteria() Function is that it can accept only one field as first parameter. But, there is a way to use more than one field for the Filter condition on the Form. Ask the User to enter conditions for two different fields separately and run the BuildCriteria() Function also separately to obtain the results. Join both results with AND/OR Logical operators to filter the data.

The following example Code uses OrderID and ShipName field values to Filter data on the Orders Form.


  1. Create a Copy of the Orders Form and name the Form as Orders2
  2. .
  3. Open the Form in Design View.

  4. Display the Code Module of the Form ( View - -> Code).

  5. Copy and Paste the following Code into the Module replacing the existing Code:




Private Sub cmdFilter_Click()
Dim txtOrderNumber, txtOrderfilter As String
Dim txtShipName, txtShipNameFilter As String
Dim msg As String, resp, txtFilter As String

txtOrderNumber = InputBox("OrderID Value/Range of Values to Filter")
txtShipName = InputBox("ShipName/Partial Text to Match")

If Len(txtOrderNumber) > 0 Then
txtOrderfilter = BuildCriteria("OrderID", dbLong, txtOrderNumber)
End If

If Len(txtShipName) > 0 Then
txtShipNameFilter = BuildCriteria("ShipName", dbText, txtShipName)
End If

If Len(txtOrderfilter) > 0 And Len(txtShipNameFilter) > 0 Then
msg = "1. Filter items-that matches both filter conditions" & vbCr & vbCr
msg = msg & "2. Matches either one or Both conditions" & vbCr & vbCr
msg = msg & "3. Cancel"
Do While resp <> 1 And resp <> 2 And resp <> 3
resp = InputBox(msg)
Loop
Select Case resp
Case 3
Exit Sub
Case 1
txtFilter = txtOrderfilter & " AND " & txtShipNameFilter
Case 2
txtFilter = txtOrderfilter & " OR " & txtShipNameFilter
End Select
Else
txtFilter = txtOrderfilter & txtShipNameFilter
If Len(Trim(txtFilter)) = 0 Then
Exit Sub
End If
End If

Me.FilterOn = False
If Len(Trim(txtFilter)) > 0 Then
Me.Filter = txtFilter
Me.FilterOn = True
End If

End Sub


The first two InputBox() Functions collects the Filter Criteria for OrderID and ShipName Field values separately. Next steps Validates the User responses and Builds the criteria strings in txtOrderFilter and txtShipNameFilter Variables.

If both Variables have filter conditions in them then the User response is collected to check whether he/she needs the result set that meets both conditions (AND) or result set that meets any one of the conditions or both (OR).

The Filter Strings are joined accordingly to obtain the intended result. It is not necessary that the User should always provide both set of Criteria Values (for Orderld and ShipName) all the time. They can use only one Field for entering Criteria and ignore the other.



StumbleUpon Toolbar



Office Assistant and MsgBox Menus-3
Office Assistant and MsgBox Menus-2
Office Assistant and MsgBox Menus
Color and Picture in MsgBox
Microsoft Excel Power in Access

Labels:

0 Comments:

Post a Comment

Note:Comments subject to Review by Blog Author before displaying.

Links to this post:

Create a Link

<< Home


Creative Commons License
Learn MS-Access Tips and Tricks by msaccesstips.com is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.5 India License.



This Page is best viewed with 1280 x 1024 Resolution

   FEATURED LINKS
SITEMAP
Command Button Animation
3D Headings on Forms
MsgBox & Office Assistant
Reminder Ticker
MS-Access & E-Mails
Automated E-Mail Alerts
MsgBox with Options Menu
Colorful Command Buttons
Configure Lotus Notes
Alerts through Network
Running this site has become a costly affair as the revenue from Ads is not sufficient to support it. If you find these pages informative & useful and would like to extend a helping hand, then please do it here.





Link Back to us with this Button

Learn MS-Access

Copy and Paste this HTML Code in your Webpage


Add to Technorati Favorites

Programming Blogs - Blog Catalog Blog Directory
Powered by FeedBurner
Add to Google

Software
Computers blogs
TopOfBlogs




AddMe - Search Engine Optimization Submit Your Site Free!
Go BlogZ Ave Blogs
eBlogzilla Changing LINKS
LS Blogs Blogarama
blog search directory BlogUniverse
Find Blogs in Directory RSS Directory
blogskinny.com ShowcaseBlogs.com
Amfibi

Search Engine Optimization and SEO Tools
Dmegs Web Directory Takeaway for Sale Businesses For Sale
Free Submission Directory Free site submission

Free Listing
 





Free Page Rank Checker

AddThis Social Bookmark Button

Enter your email address:

Delivered by FeedBurner



Top Blogs


Microsoft Access is the Jewell among MS-Office suite of Applications. Its Security features are excellent and works fine in Network environment. MS-Access can link/upload data from any Data Source. Applications that you design should be user-friendly and visually pleasing too. Here I would like to share my experience in Microsoft Access Programming with you and I am sure that you will find them interesting too.

My Photo
Name: Ramachandran Pillai
Location: Cochin, India

I am not an Access Guru and not through MS-Access yet. More to learn and I don’t think that aspect has any end because others have their own style of using this tool. We can learn lot more tricks, other than what we already know, from others too. My programming skills in COBOL, BASIC, Turbo-C, dBase, FoxPro, Visual Basic & Basic HTML attained through self-learning. I wrote my first COBOL Program in 1975 for ICL1901, 3rd Generation Main Frame Computer. Worked as a Computer Operator (NCR VRX8555 Mainframe Machine upto 1990) with M/s. Y.B.A. Kanoo, Saudi Arabia. Started using MS-Access Ver.2 in 1996, when dBase III+ and Foxbase (later version Foxpro) were my favorite DBMS. During Last 13 Year period I have developed more than 45 In-House Applications (medium & small) under MS-Access for our Organization, a leading Automotive Company in Oman. All the Applications are fully Secured and runs under Windows Network. It is my pleasure to share my experience with others. Anything interesting that you would like to share with me, please do. My E-mail Address: aprpillai@msaccesstips.com


If you need a Demo of any of the Topic explained here, send me an E-mail to: aprpillai@msaccesstips.com
with the Topic Description, I shall try to send a sample database to you.


Access Tips | Email | Reports | Report Tricks | Graphs | Forms | Menus | Animation | Security | Internet | How TOs | Linking | Query | Progress Meter | Alerts | Process Tips | Access Functions |




Site Designed by:www.msaccesstips.com