<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
Friday, November 07, 2008

Sum Min Max Avg ParamArray

I know your immediate response after looking at the Title will be, "I know all those things, tell me something that I don't know". Well, if you haven't come across the last item (that is an odd one) in the Title before, then that is what I am trying to do here, read on. The first four words are very familiar to us they are Built-in Functions in MS-Access and Worksheet Functions in Excel.


We will catch up with the last one later, after checking the usage of Min() Function (will represent the first four items in the title) in Excel and why we have some difficulty with it in MS-Access when compared with Microsoft Excel.


We are not forgetting the other Functions DCount(), DSum(), DMin(), DMax() and DAvg() of Access at all.


Let us look at the usage of Min() Worksheet Function in Excel. It can find the minimum Value from a Range of Cells in a single Column, from a Row of Cells across Columns or from a Range of Cells spread over several Columns and Rows.



But, when we come back to MS-Access the Min() Function can be used only in a single column (on a single Field) of Data in Query and in Header/Footer Sections of Forms or Reports. Then what do we do to find the Minimum value from more than one Field of data?


Have a look at the sample Table given below to get the gravity of the issue we are in here.

Source Data for Minimum Function


We have received Quotations for Electronic Items from three different Suppliers and we need to know which one is the lowest and from which Supplier? In this case our Min() Function has no use here unless we re-organize the above data into the following format:



Data Table in Different Format


To get the required result out this data we need two Queries and we will ignore the duplication of Descriptions, Supplier Names and the Table size in Records etc. for now.


  1. Need one Total Query to group on Desc field and the Min() Function to find the minimum Value from the Values Field.

  2. Need a second Query, using the first Query and the Table above as Source, JOINed on Desc and MinOfValues Columns of the Total Query with the Desc and Values Fields of the Table to pick all the records from the Table matching with minimum quoted values and Description.



I consider these steps are excessive work and I know you will agree too. Instead, we can write a User Defined Function with the use of ParamArray and pass the Field Names to the Function and find the Minimum Value from the list. Here is a simple Function with the use of ParamArray declaration to find the Minimum Value from a List of Values passed to it.



Public Function myMin(ParamArray InputArray() As Variant) As Double
'------------------------------------------------------------------
'Author : a.p.r. pillai
'Date : November-2008
'URL : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------------------
Dim arrayLength As Integer, rtn As Double, j As Integer

'calculate number of elements in Array
arrayLength = UBound(InputArray())

'initialize Null values to 0
For j = 0 To arrayLength
InputArray(j) = Nz(InputArray(j), 0)
Next
'initialize variable with 1st element value
'or if it is zero then a value with high magnitude
rtn = IIf(InputArray(0) = 0, 9999999999#, InputArray(0))

For j = 0 To arrayLength
If InputArray(j) = 0 Then GoTo nextitem
If InputArray(j) < rtn Then
rtn = InputArray(j)
End If
nextitem:
Next

myMin = rtn
End Function


Copy and Paste the above Code into a Global Module and save it.


Few simple rules must be kept in mind while writing User Defined Functions using the ParamArray declaration in the Parameter list of the Function.


  1. While declaring the Function, the Parameter Variable InputArray() (or any other name you prefer) must be declared with the keyword ParamArray, in place of ByRef or ByVal we normally use to declare parameters to functions.

  2. The Data Type must be Variant.

  3. The ParamArray declaration must be the last item in the Parameter list if the UDF accepts more than one Parameter.

  4. The Optional parameter declarations should not appear before the ParamArray declaration.

  5. Since the data type is Variant it can accept any type of values.


With the use of the above myMin() Function we have created a Query on the first Table given above. The SQL and the result image of the Query in Datasheet View are given below.


SELECT MaterialQuote.Desc,
MaterialQuote.Supplier1,
MaterialQuote.Supplier2,
MaterialQuote.Supplier3,
mymin([supplier1],[supplier2],[supplier3]) AS Minimum,
IIf([minimum]=[supplier1],"Supplier1",IIf([minimum]=[supplier2],"Supplier2",IIf([minimum]=[supplier3],"Supplier3",""))) AS Quote
FROM MaterialQuote;


Result Data of myMin() Function

In the above example we have used only three Field Values to pass to the Function and these can vary depending on your requirement.


A modified version of the same Function is given below that accepts a Calculation Type value (range 0 to 3) as first Parameter and depending on that we can find Summary, Minimum, Maximum, or Average of values passed to it through the InputArray() Variable.



Public Function SMMAvg(ByVal calcType As Integer, ParamArray InputArray() As Variant) As Double
'------------------------------------------------------------------------
'calType : 0 = Summary
' : 1 = Minimum
' : 2 = Maximum
' : 3 = Average
'------------------------------------------------------------------------
'Author : a.p.r. pillai
'Date : November 2008
'URL : www.msaccesstips.com
'All Rights Reserved by www.msaccesstips.com
'------------------------------------------------------------------------
Dim rtn, j As Integer, arrayLength As Integer
Dim NewValue As Variant

On Error GoTo SMMAvg_Err

If calcType < 0 Or calcType > 3 Then
MsgBox "Valid calcType Values 0 - 3 only", , "SMMAvg()"
Exit Function
End If

arrayLength = UBound(InputArray())
For j = 0 To arrayLength
InputArray(j) = Nz(InputArray(j), 0)
Next

Select Case calcType
Case 1
rtn = InputArray(0)
rtn = IIf(rtn = 0, 9999999999#, rtn)
Case 2
rtn = InputArray(0)
Case Else
rtn = 0
End Select

For j = 0 To arrayLength
NewValue = InputArray(j)
If NewValue = 0 Then GoTo nextitem
Select Case calcType
Case 0, 3
rtn = rtn + NewValue
Case 1
rtn = IIf(NewValue < rtn, NewValue, rtn)
Case 2
rtn = IIf(NewValue > rtn, NewValue, rtn)
End Select
nextitem:
Next

If calcType = 3 Then
rtn = rtn / (arrayLength + 1)
End If

SMMAvg = rtn

SMMAvg_Exit:
Exit Function

SMMAvg_Err:
MsgBox Err.Description, , "SMMAVG()"
SMMAvg = 0
Resume SMMAvg_Exit

End Function


The Function name was defined using the first letters of the Calculation Types that the Function can perform and I hope you like it too.


When any of the values in the InputArray() element is Zero then that is ignored and will not be taken as minimum value.


We can use this Function in Text Boxes on Forms or Reports by passing Values from other Controls. Use it at your own risk.


StumbleUpon Toolbar



Access Live Data in Excel-2
MS-Access Live Data in Excel
Database Connection String Properties
Opening Excel Database Directly
Display Excel Value Directly on Form

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