VBA Calculation with Variables 03-25-10

Hello:  I am trying to calculate an average of numbers in an array for a 
series of individuals.  The quantity of numbers may range from none to more 
than 20 and I want to average no less than 2 numbers nor more than 8 numbers. 
 I am using Select Case as I thought that a nested If..Then.. Else would be 
cumbersome.  The calculation for 8 numbers works (with the exception of a 
rounding issue which will be explained further down), but when I want to 
calculate averages for any fewer than 8 numbers it returns erroneous values.  
It seems as if it is holding onto additional numbers so the averages are much 
higher than they should be.

Following is the basic code:

   Dim avg As Single

' calculate average if >=2, <=8 valid numbers
        avg = 0
        
    Select Case 8 - 0
         Case 8
            If holdnumbers(0) > 0 And holdnumbers(1) > 0 And holdnumbers(2) 
> 0 And holdnumbers(3) > 0 And holdnumbers(4) > 0 And holdnumbers(5) > 0 And 
holdnumbers(6) > 0 And holdnumbers(7) > 0 Then
                golfavg = (holdnumbers(0) + holdnumbers(1) + holdnumbers(2) 
+ holdnumbers(3) + holdnumbers(4) + holdnumbers(5) + holdnumbers(6) + 
holdnumbers(7)) / 8
            End If

        Case 7
            If holdnumbers(0) > 0 And holdnumbers(1) > 0 And holdnumbers(2) 
> 0 And holdnumbers(3) > 0 And holdnumbers(4) > 0 And holdnumbers(5) > 0 And 
holdnumbers(6) > 0 Then
                golfavg = (holdnumbers(0) + holdnumbers(1) + holdnumbers(2) 
+ holdnumbers(3) + holdnumbers(4) + holdnumbers(5) + holdnumbers(6)) / 7
            End If
    
and so forth to End Select.

holdnumbers(0-7) is also cleared (set to 0) after every calculation as so:

    ' reset score array
        holdnumbers(0) = 0
        holdnumbers(1) = 0
        holdnumbers(2) = 0

Also, in calculating the average the result is returned rounded to one 
decimal place, though I have the worksheet set to two decimal places.  The 
calculated number is set as Single.   For example,  a worksheet average 
calculated as 87.69 is returned by the code as 87.50.

Thanks in advance for any advice you can provide.
0
Utf
3/25/2010 10:30:01 PM
excel.programming 6508 articles. 2 followers. Follow

1 Replies
605 Views

Similar Articles

[PageSpeed] 21

Kind of confusing and overkill. What is the select case using

selectcase.range("a1")
???


-- 
Don Guillett
Microsoft MVP Excel
SalesAid Software
dguillett@gmail.com
"Hawk" <Hawk@discussions.microsoft.com> wrote in message 
news:5C089260-312F-4A77-9D39-EFE509BE5C17@microsoft.com...
> Hello:  I am trying to calculate an average of numbers in an array for a
> series of individuals.  The quantity of numbers may range from none to 
> more
> than 20 and I want to average no less than 2 numbers nor more than 8 
> numbers.
> I am using Select Case as I thought that a nested If..Then.. Else would be
> cumbersome.  The calculation for 8 numbers works (with the exception of a
> rounding issue which will be explained further down), but when I want to
> calculate averages for any fewer than 8 numbers it returns erroneous 
> values.
> It seems as if it is holding onto additional numbers so the averages are 
> much
> higher than they should be.
>
> Following is the basic code:
>
>   Dim avg As Single
>
> ' calculate average if >=2, <=8 valid numbers
>        avg = 0
>
>    Select Case 8 - 0
>         Case 8
>            If holdnumbers(0) > 0 And holdnumbers(1) > 0 And holdnumbers(2)
>> 0 And holdnumbers(3) > 0 And holdnumbers(4) > 0 And holdnumbers(5) > 0 
>> And
> holdnumbers(6) > 0 And holdnumbers(7) > 0 Then
>                golfavg = (holdnumbers(0) + holdnumbers(1) + holdnumbers(2)
> + holdnumbers(3) + holdnumbers(4) + holdnumbers(5) + holdnumbers(6) +
> holdnumbers(7)) / 8
>            End If
>
>        Case 7
>            If holdnumbers(0) > 0 And holdnumbers(1) > 0 And holdnumbers(2)
>> 0 And holdnumbers(3) > 0 And holdnumbers(4) > 0 And holdnumbers(5) > 0 
>> And
> holdnumbers(6) > 0 Then
>                golfavg = (holdnumbers(0) + holdnumbers(1) + holdnumbers(2)
> + holdnumbers(3) + holdnumbers(4) + holdnumbers(5) + holdnumbers(6)) / 7
>            End If
>
> and so forth to End Select.
>
> holdnumbers(0-7) is also cleared (set to 0) after every calculation as so:
>
>    ' reset score array
>        holdnumbers(0) = 0
>        holdnumbers(1) = 0
>        holdnumbers(2) = 0
>
> Also, in calculating the average the result is returned rounded to one
> decimal place, though I have the worksheet set to two decimal places.  The
> calculated number is set as Single.   For example,  a worksheet average
> calculated as 87.69 is returned by the code as 87.50.
>
> Thanks in advance for any advice you can provide. 

0
Don
3/25/2010 11:39:50 PM
Reply:

Similar Artilces:

VBA code to say Yes or No if any VBA code is present in ActiveWork
Using XL 2003 & 97 Would like hit Ctrl+Shift+V and have an answer either yes or no as to the presence of Any VBA code in the Active Workbook. I do know that about the VBA editor/Explorer or to press the Run Macro button and get a list from various sources . I would like to stay at the keyboard and process a series of macros including one to let me know if I even need to evoke the VBA explorer. TIA Dennis There is no bootstrap macro to tell you whether you have macros or not. If there were there would be no limit to virus writers. --- HTH, David McRitchie, Microsoft MVP - Excel ...

Print, Merged Cells, and VBA
Hello I'm looking for a code that will help me with a print job for a worksheet. There are a lot of merged cells and a lot of "IF"s to be used in the VBA for range selection. Thanks in advance, Sarr ...

Use VBA to update Access table or Query from Excel
Can I use VBA to update Access table or Query from Excel? Thanks in advance Hi Leungkong, > Can I use VBA to update Access table or Query from Excel? Of course, using ADO or DAO. See: http://www.erlandsendata.no/english/index.php?d=envbadacexportado Regards, Jan Karel Pieterse Excel MVP http://www.jkp-ads.com Hi Jan, Thanks. I think ADO is what I want. But I am not only want to export from excel to access. I want to edit some data in access table. For example, Access has a table "ProductList" I want to use Excel to call the product by "Pro...

Notes #10
I'm wondering if it's possible to send notes from a smart phone to outlook/one note? Thank you for any answers. Probably depends on the sync software supplied with your phone "maxermil" <maxermil@discussions.microsoft.com> wrote in message news:7D25A6D8-48C7-4E6B-B8F5-8BE0BC66EA2E@microsoft.com... > I'm wondering if it's possible to send notes from a smart phone to > outlook/one note? Thank you for any answers. ...

Calculate difference in hours of actual day/time data versus fixed weekdays
Hi, I am faced with a problem of performing calculations on dates and weekdays. I have a planned schedule of events that occur regularly on a particular day of the week. (e.g every Wed 02:00). I am currently performing an analysis based on realtime data with the following format "Thu 1/15/2004 17:00" (ddd mm/dd/yyyy hh:mm). I need to calculate by how many hours the event is early or late. See below for an illustration: Event | Planned Time | Instance 1 of event | | |Actual Difference| -----------------------------------------------------...

VBA and Scheduled task in Outlook
Hi, how can I: a) pull the query from somewhere and send it by e-mail automatically. E.g. I want to take a temperature table from http://www.wunderground.com/history/airport/EHAM/2009/7/10/DailyHistory.html?req_city=NA&req_state=NA&req_statename=NA where 2009/7/10 is the date of yesterday put it into an e-mail and send it automatically each day at 8 o'clock? b) if this is not possible, how can I send an e-mail with the attachment c:\Documents\query20090710.xls each day at 8 o'clock? my boss wants this automatized, I know how to write the VBA code for Excel, but don'...

vba select field
Hi, having a button on a form, is it possible to select only some fields (all from the same table) of the current record instead of all fields? I've tried this code: RunCommand acCmdSelectRecord RunCommand acCmdCopy Forse dipende dei dati nel record. but it selects ALL fields in the form. Thank you. Remigio hi, On 10.04.2010 18:01, remigio wrote: > having a button on a form, is it possible to select only some fields > (all from the same table) of the current record instead of all fields? > I've tried this code: > > RunCommand acCmdSelectRecord &...

VLOOKUP in VBA
On the worksheet I can insert in a cell =VLOOKUP(C5, Hobokee.xls!AcsLow, 2) and it works perfectly, looks up the value in column 2 of the range named AcsLow in the same workbook. But elswhere I want in a macro to lookup the same table and assign the result to a variable BalAmt. BalAmt = VLOOKUP(AccNum, Hobokee.xls!AcsLow, 2) does not work. It gives a function not defined error on Hobokee. If instead of Hobokee I put Workbooks("Hobokee"), it gives function not defined error for VLOOKUP which it changes to VLookup. I have been overVLOOKUP in the Help file and see nothing wrong. W...

Number Format #10
Hello I've got a large spreadsheet which was imported. Apart from the first 2 columns, the rows consist of number which I need to filter, but this isn't working. Then I noticed an apostrophe before each number in every cell, which doesn't show in the cell but up in the formula/text bar. I've set all the columns to numbers but the apostrophe won't go away. Please can someone tell me how I can without having to go into each cell as there are hundreds. Thank you J Select all the columns with these "numbers" in them, then right click the tab at the bottom of t...

Excel VBA/Macro programming for beginners
Hi all, I know a bit VB 6.0 programming. Will it help me to write exce vba/macro(same thing?).can anybody help me by providing some fre websites where i can have informations/codes for VBA/macro. Please tell me how could i make a *command Button * in a cell in th excel sheet -- sdebu_200 ----------------------------------------------------------------------- sdebu_2000's Profile: http://www.officehelp.in/member.php?userid=430 View this thread: http://www.officehelp.in/showthread.php?t=118812 Posted from - http://www.officehelp.i Try David McRitchie's "getting started with mac...

Turn pc speaker on/off with vba code
Is this possible? Thanks I found something here on how to do it withVBScript. You can probably modify it to work in VBA http://www.pcreview.co.uk/forums/thread-1468591.php -- HTH, Barb Reinhardt "David" wrote: > Is this possible? > Thanks Thanks Barb I'll have a go (I need to improve my web searching skills) "Barb Reinhardt" wrote: > I found something here on how to do it withVBScript. You can probably modify > it to work in VBA > > http://www.pcreview.co.uk/forums/thread-1468591.php > -- > HTH, > ...

Revamp how Finance charges are calculated (see #8661494)
Support Incident #8661494 Our client has an issue with the way finance charges are calculating. I am including his e-mail for description. He points out most companies do it his way. We have read the manual and search the knowledge base but can't find much information on how to make this work the way he wants. We advised him to run his financing charges after the third of the month. But this will only work if ALL his invoices are billed on the second. We advised him, as was read in the manual, that if he was applying payments (which would be the norm) the system reads that b...

Outlook client 07-11-03
I have installed the newest Outlook client for MS CRM yesterday and it was working pretty well. I logged off lastnight and when I logged on this morning the Outlook CRM ToolBar is no longer visible. Any ideas on how to reactivate this? ...

Loading a Form from VBA
Hi all, I'd like a module to open and load a form in my Access 2003 database... How can I do this? Use the OpenForm method. Look in the Help file for details. -- Doug Steele, Microsoft Access MVP http://I.Am/DougSteele (no e-mails, please!) "Mike" <michael.leon.schwartz@gmail.com> wrote in message news:1184770076.109526.207900@o11g2000prd.googlegroups.com... > Hi all, I'd like a module to open and load a form in my Access 2003 > database... How can I do this? > On Jul 18, 10:58 am, "Douglas J. Steele" <NOSPAM_djsteele@NOSPAM_canada.com&g...

microsoft security essentials 07-30-10
Any body using MS security essentials? Why so many updates is it necessary to down load that many, using a lot of disk space! Hi, pacca. Yes! MSE is doing a fine job for me and has ever since it first appeared last year. I have Windows Update set to download the updates and ask me when to install them. Then I set MSE to check for the latest definitions before running its weekly scan. Each downloaded Definition Update apparently overwrites the previous one, so they do not continuously gobble up more disk space. At least, my entire C:\Program Files\Microsoft Securit...

Excel and VBA
I am very interested in learning more about using VBA in office, especially Excel. Can you post some resources (online, books, etc) that can be used to help learn about using Visual Basic in office. Thanks! Here's a good place to start: http://www.contextures.com/xlbooks.html Does that help? *********** Regards, Ron XL2002, WinXP "Bob Sinclair" wrote: > I am very interested in learning more about using VBA in office, especially > Excel. Can you post some resources (online, books, etc) that can be used to > help learn about using Visual Basic in office. >...

VBA Customization
Is there a way to get the name of the current company through VBA in Great Plains 8.0? Thanks for all your help. open GreatPlains. Add the current window, it will add the Toolbar then add fields choose the company name on the top left after the user id. >-----Original Message----- >Is there a way to get the name of the current company through VBA in Great >Plains 8.0? > >Thanks for all your help. > > > >. > Thanks. I tried, but I couldn't add company name to the field list. It opens up the login screen instead. Any thoughts? Thanks again. "ger...

Calculation query, how to avoid extreme values?
Good morning, I have 1 table with a few fields (A, B, C) that I'm using for various calculations. For various reasons are some of the input "weird" and I want to leave that out of the calculation (average). For example, Field A requires > 0 AND < 100, B < 400 Now, if one record doesn't fullfil A requirement I don't want to use it for A's average calculation BUT I want to use it for B's average calculation (if it satisfy B's requirement). This means that if I use the query criteria A: >0 AND <100 it will filter out all other records an...

Calculating the column
Hi, Sorry to ask but... I want to calculate the column for a vert.search function. Say a want to start the search at column (2*3) [=6], how can I transform the "6" in "F"? Thanks very much in advance. Fred Is this for VBA? If yes, you don't need to change the number to letters. activesheet.columns(6) or activesheet.columns(2*3) would work fine. NO wrote: > > Hi, > Sorry to ask but... > I want to calculate the column for a vert.search function. > Say a want to start the search at column (2*3) [=6], how can I transform the > "6" in "...

Run VBA without show
I want excel to run the VBA code without showing me what it is doing. Which code should i use for that? Sub RunWithoutShow() Application.ScreenUpdating = False 'Paste the vba code here 'end of code 'Change screenupdating property to true Application.ScreenUpdating = True End Sub I hope this helps... Selva V Pasupathy For more on Excel, VBA, & other Resources Please visit: http://socko.wordpress.com You may also (inserting into quote from code example bellow from Socko) Use Application.Visible property to hide the application entirely Sub RunWithoutShow() Appli...

Form Controls vs VBA controls
I am new to VBA so just finding my feet, can anyone help me with th differences between an excel control (i.e. one from the form toolbox lets say a checkBox and a vba checkBox? From trying the two controls the I have noticed is that you canno capture the change event of the VBA checkbox in the code module, it ha to be done via the sheet (i.e. checkbox on sheet1, code goes in chang event on sheet1) the control is placed on, is this correct? What woul you do if you have three sheets with the same controls just differen data, do you really have to code the control 3 times? The excel control ho...

How do I use a check box to accept a calculation
I am trying to create a ledger that has both current balance and the balance my bank has. Right now it can only tell me what my current balance is. My question is, How can I use a check box to initiate a calculation? This way is there is no check in the box then the calculation does not happen, but when I put a check in the box the calculation happens. This way when my bank shows something that has posted I can place the check and automatically balance my check book. Could you specify exactly, what your ledger format is? "Joejoethecrackman" wrote: > I am trying to cre...

Referencing a ComboBox in VBA
Hi, I am using Excel 2007. I want to run some code in my Workbook_Open() Sub that fills a combo box on one of my Worksheets (I will call it myCombo on mySheet). I tried the following code and it did not work: myCombo.Clear myCombo.AddItem "Item One" myCombo.AddItem "Item Two" myCombo.AddItem "Item Three" I assume that the problem is that within the Workbook_Open() Sub, the reference to myCombo is not valid. Can anyone tell me if/how I can get a valid reference to myCombo (on mySheet)? Thanks in advance, Paul Kraemer -- Paul Krae...

inserting and renaming a sheet vba
Instead of having 2 lines of code, one to insert a new sheet and one t rename it, is there a way to insert a sheet with particular name i one go -- Matt Housto ----------------------------------------------------------------------- Matt Houston's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=451 View this thread: http://www.excelforum.com/showthread.php?threadid=26717 ...

VBA??
Is there any way i can input certain numbers and they change to words. for example. 2001 Omagh 2002 Craigavon 2027 Housing Benefit 2036 IT Replacment any help please thanks monty If you mean you want to enter 2001 in cell A1 and have "Omagh" magically appear in its place when you hit the return key, I don't think it can be done. However, if you enter 2001 in cell A1 and have a VLOOKUP formula in cell B1, with reference data stored elsewhere in the sprdsht, that is easily done. Monty How many substitutes do you have? You are probably best to set up a separate table with ...