#### why does my code loop?

```I have the following code that's meant to calculate average times
between open and close dates.  But for some reason that I can't figure
out its looping where I don't expect it to loop.  I've added MsgBoxes
throughout to try to help but I'm stuck.  Does anyone know why this
appears to be looping outside of the for loop?

Function LagAverage(OpenDates As Range, PNum As Range) As Single

MsgBox "starting now"

EOPeriod = Sheets("Hub").Range("B8").Value - 1 + PNum * 28

TimeSum = 0
Counter = 0

For Each ODate In OpenDates

MsgBox ODate.Value

If Not IsEmpty(ODate) Then

MsgBox "past 1"

If ODate.Value <= EOPeriod Then

MsgBox "past 2"

If Not IsEmpty(ODate.Offset(0, 6)) Then

MsgBox "past 3"

If ODate.Offset(0, 6).Value <= EOPeriod Then

TimeSum = TimeSum + (ODate.Offset(0, 6).Value
- ODate.Value)
Counter = Counter + 1
MsgBox Counter
MsgBox TimeSum

ElseIf (EOPeriod - ODate.Value) >= 30 Then

TimeSum = TimeSum + (EOPeriod - ODate.Value)
Counter = Counter + 1

End If

ElseIf (EOPeriod - ODate.Value) >= 30 Then

TimeSum = TimeSum + (EOPeriod - ODate.Value)
Counter = Counter + 1

End If

End If

End If

Next ODate

MsgBox "exited for loop"

AverageDates = TimeSum / Counter

MsgBox TimeSum
MsgBox Counter

LagAverage = AverageDates

End Function
```
 0
MLT
3/16/2010 2:38:15 PM
excel 39879 articles. 2 followers.

3 Replies
1756 Views

Similar Articles

[PageSpeed] 2

```I can't get it to loop except where I would expect it. Where are you seeing
extra loops, and or what data?

--

HTH

Bob

"MLT" <mlthornton@gmail.com> wrote in message
news:a0939d00-cdc1-4d8b-8ec5-0dab9779b55d@q16g2000yqq.googlegroups.com...
>I have the following code that's meant to calculate average times
> between open and close dates.  But for some reason that I can't figure
> out its looping where I don't expect it to loop.  I've added MsgBoxes
> throughout to try to help but I'm stuck.  Does anyone know why this
> appears to be looping outside of the for loop?
>
> Function LagAverage(OpenDates As Range, PNum As Range) As Single
>
>    MsgBox "starting now"
>
>    EOPeriod = Sheets("Hub").Range("B8").Value - 1 + PNum * 28
>
>    TimeSum = 0
>    Counter = 0
>
>    For Each ODate In OpenDates
>
>    MsgBox ODate.Value
>
>        If Not IsEmpty(ODate) Then
>
>        MsgBox "past 1"
>
>            If ODate.Value <= EOPeriod Then
>
>            MsgBox "past 2"
>
>                If Not IsEmpty(ODate.Offset(0, 6)) Then
>
>                MsgBox "past 3"
>
>                    If ODate.Offset(0, 6).Value <= EOPeriod Then
>
>                        TimeSum = TimeSum + (ODate.Offset(0, 6).Value
> - ODate.Value)
>                        Counter = Counter + 1
>                        MsgBox Counter
>                        MsgBox TimeSum
>
>                    ElseIf (EOPeriod - ODate.Value) >= 30 Then
>
>                        TimeSum = TimeSum + (EOPeriod - ODate.Value)
>                        Counter = Counter + 1
>
>                    End If
>
>                ElseIf (EOPeriod - ODate.Value) >= 30 Then
>
>                    TimeSum = TimeSum + (EOPeriod - ODate.Value)
>                    Counter = Counter + 1
>
>                End If
>
>            End If
>
>        End If
>
>    Next ODate
>
>    MsgBox "exited for loop"
>
>    AverageDates = TimeSum / Counter
>
>    MsgBox TimeSum
>    MsgBox Counter
>
>    LagAverage = AverageDates
>
> End Function

```
 0
Bob
3/16/2010 4:27:48 PM
```Custom User-Defined-Functions might be run multiple times depending on the
re-calculation dependency tree, event code, and other formulas within your
workbook.  Use a clean workbook for code checking, and if it doesn't loop in
an otherwise empty workbook, then your code is as good as possible.

One other item to considcer is passing

Sheets("Hub").Range("B8").Value

as a parameter rather than hard-coding it.  If the cell changes, a re-calc
will not be fired, and it the cell is moved (possible due to row insertion
or deletion) the function will not be able to call the value of the new
location.  Using a named range will fix part of that (the movement, not the
re-calc.)

HTH,
Bernie
MS Excel MVP

"MLT" <mlthornton@gmail.com> wrote in message
news:a0939d00-cdc1-4d8b-8ec5-0dab9779b55d@q16g2000yqq.googlegroups.com...
>I have the following code that's meant to calculate average times
> between open and close dates.  But for some reason that I can't figure
> out its looping where I don't expect it to loop.  I've added MsgBoxes
> throughout to try to help but I'm stuck.  Does anyone know why this
> appears to be looping outside of the for loop?
>
> Function LagAverage(OpenDates As Range, PNum As Range) As Single
>
>    MsgBox "starting now"
>
>    EOPeriod = Sheets("Hub").Range("B8").Value - 1 + PNum * 28
>
>    TimeSum = 0
>    Counter = 0
>
>    For Each ODate In OpenDates
>
>    MsgBox ODate.Value
>
>        If Not IsEmpty(ODate) Then
>
>        MsgBox "past 1"
>
>            If ODate.Value <= EOPeriod Then
>
>            MsgBox "past 2"
>
>                If Not IsEmpty(ODate.Offset(0, 6)) Then
>
>                MsgBox "past 3"
>
>                    If ODate.Offset(0, 6).Value <= EOPeriod Then
>
>                        TimeSum = TimeSum + (ODate.Offset(0, 6).Value
> - ODate.Value)
>                        Counter = Counter + 1
>                        MsgBox Counter
>                        MsgBox TimeSum
>
>                    ElseIf (EOPeriod - ODate.Value) >= 30 Then
>
>                        TimeSum = TimeSum + (EOPeriod - ODate.Value)
>                        Counter = Counter + 1
>
>                    End If
>
>                ElseIf (EOPeriod - ODate.Value) >= 30 Then
>
>                    TimeSum = TimeSum + (EOPeriod - ODate.Value)
>                    Counter = Counter + 1
>
>                End If
>
>            End If
>
>        End If
>
>    Next ODate
>
>    MsgBox "exited for loop"
>
>    AverageDates = TimeSum / Counter
>
>    MsgBox TimeSum
>    MsgBox Counter
>
>    LagAverage = AverageDates
>
> End Function

```
 0
Bernie
3/16/2010 5:00:40 PM
```That must have been it.  I put this same code in clean workbook and it
ran as I expected (didn't run through multiple times).  Before, it was
running through the entire code (not just the for loop) 3 times.
Thanks for the help!
```
 0
MLT
3/16/2010 8:20:39 PM
 Reply:

Similar Artilces:

Integrate Paycodes, benefit codes and deduction codes
Has anyone used integration manager to update new pay rates, deduction amounts and benefit amounts for employees? At the beginning of each year, our company gives pay increases and we need to update the pay codes, deduction codes and benefit codes for 40 employees, which we get the information from a spreadsheet. I thought that maybe I could use integration manager to update the pay, benefit and deduction codes instead of going into each employee's card, which is time consuming. Thanks, Laura Integration Manager will allow you to do this. Use the Payroll Master Destination. one ...

zip codes don't merge #2
I am trying to mail merge w/ Word 2000 the names and addresses in my worksheet. When I get to the part to choose the format for the mailing labels, I choose F1, F2, etc. to F6 (which is the zip code column). A few do get there, but the vast majority stop at the state, leaving off the entire zip code. I have gone to menu/format and selected text in the number tab. I have gone to format/cells and chosen special/zip code in the number tab. I've read Excel for Dummies. Please help me. TIA bb ...

concatenating two vendor codes
My company recently changed the vendor codes and now I end up with two separate sets of data for each vendor. Obviously I could just leave the vendor code field out. I don't want to do that so what I need to do is concatenate the two codes. Example Vendor Code Vendor Name 123 Joe's Supplies ABC Joe's Supplies what I need is this Vendor Code Vendor Name 123/ABC Joe's Supplies any ideas? Rather than create a new record for each vendor, add another field to the table -- call it NewVendorCode -- and put th...

Can MS EXCEL remove duplicates and separate by color coded items ?
Can MS EXCEL remove duplicates and separate by color coded items ? I am NOT technical and have just started using MS EXCEL. Can anyone PLEASE HELP me: 1. How can I automatically remove duplicates using EXCEL ? ie the same info input more than once on different lines. Can EXCEL do this ? 2, I have color coded the text in the certain lines in terms of priority. can Excel rearrange the data by color ? If yes, How do I do it ? I think I have EXCEL '97 Thanks for your help in advance. Hi 1. You can extract the unique items to a new list using menu Data > Filter > Advanced fil...

16 bit code
Hello, I have a 16 bit code to maintain. (It is too complex to copile it to 32 bit) so all we are doing is support. Now they want to add a small feature, where I need to copy long file names in the project. I know we can not do long file name copies in vc++ (1.52). So I wrote a program in VC++(6.0) which does directory copy. My questions are 1. How can I call a 32 bit exe (I guess WinExec should work)? 2. How can I make the 16 bit to wait till the 32 bit code completes? 3. Is there any other better way to do this? (other than converting to 32 bit) Thanks. I actually do this in an old 16-bi...

VBA Code for Pasting Sheets
I would like a spreadhseet that pastes the contents of one sheet into another sheet. I like like to do this for 7 different sheets For example: I would like paste the contents form sheet titled "sheet1" into a sheet titled "data1". Continue to process for pasting "sheet2" into "data2" and "sheet3" into "data3" all way until "sheet7" and "data7". thanks, Curt Subject: Automated Copy Paste Subject: Copy/Paste Import/Export Data VBA Code On Apr 27, 10:49=A0am, Curt <C...@discussions.mi...

area codes is auto filling my own 9 digit ph# vs just area code
When I enter a phone number for a contact it autofills with my personal area code and phone number instead of just the area code. How to I change this to just autofil the area code? I am using Outlook 2007 on an ACER laptop. Make sure you have your area code entered correctly in "Dialing Properties". "Computer Dummy" wrote: > When I enter a phone number for a contact it autofills with my personal area > code and phone number instead of just the area code. How to I change this to > just autofil the area code? I am using Outlook 2007 on an ACER ...

MC/VISA joint code
Isn't there any way to combine the blocks (4* & 5*) for MC/VISA credit cards? It's a pain to have them separate because my bank posts them together. It is the same company afterall. It would save me a lot of time adding separate entries together to reconcile the statement! I do not know of a way to do what you are asking, but I have found that using the # symbol as follows works better than using the * symbol: 4############### 5############### If you use the * symbol it is a wild card with no determined length. The # symbol requires that the characters after the first d...

Money 2004 - Experian Offer
I just loaded Money 2004 Deluxe and converted my 2003 files with no problem. I decided to give the free year of credit monitoring from Experian a try but after filling everything out I get an error that the provided code has expired. I neither had nor provided any code for this offer, I only used the link from Money 2004. Now Experian was more than willing to set up a \$79 account if I wanted to proceed. Any solution out there? I have the same problem... I am looking for a FREE way to contact Microsoft about this problem. >-----Original Message----- >I just loaded Money 2004 ...

Analytical Accounting
Hi, One of my Client's is considering to go down AA path with approx 300,000 AA dimension codes. I would like to hear whether such data set is manageable from Query wizard etc. appreciate your thoughts. Good Morning PR, I found that the issue isn't the number of AA Trx Dim Codes it is the size of the AAG30000 and AAG40000 tables the more entries the longer it takes to product the report. I had one client that started having a cached SSRS report with AA information as a management level report and a different SSRS report with a more restrictive dataset for reporting ...

Change code with code?
Hi All..... I've got 31 Excel .xlsm files to modify the "Change Event" macro in. Is it possible to open and perform this with code, or must I do each one by hand? TIA Vaya con Dios, Chuck, CABGx3 If it is the same change in each sheet, it would probably be just as easy to go into the VBE, double click on the first sheet, make the correction, then copy that correction and double click the second sheet, delete and paste. Repeat the process 30 times. Takes less time than writing the code to do it. "CLR" <CLR@discussions.microsoft.com> wr...

Access 2003
I have a form that goes to a subform for searching. It works perfectly on my computer; however, when another user opens it and attempts to perform a search, they receive the Error Code 2455 message. When I debug, it gets stuck on "Me.book_subform.Form.Filter = strWhereSearch" and says that book_subform cannot be found. It isn't a rights issue, it isn't a mapping issue. What am I missing? check your naming. This is an issue that often confused. In this syntax: Me.book_subform.Form.Filter > = strWhereSearch book_subform is the name of the subform control on the main ...

Write a code by code
How can I write a code from procedure to some Workbook's ThisWorkbook? With procedure1 a make Workbook with a table. I need to write Auto_Close procedure to ThisWorkbook which makes some controls before I close it. Is it possible? <jenista.j@discussions.microsoft.com> wrote in message news:0be501c52fab\$ba0b6830\$a601280a@phx.gbl... > How can I write a code from procedure to some Workbook's > ThisWorkbook? With procedure1 a make Workbook with a table. > I need to write Auto_Close procedure to ThisWorkbook which > makes some controls before I close it. Is it possible? ...

Coding Duplicate Records
How can I code that a record is to be "K" kept or "D" deleted when compared to its next row? Example: A sorted file by Address BEFORE LastName Address Sales Date Keep/Delete 1. WASSEM 0N642 TITUS PL 67,500 6/25/2001 2. HART 0N655 E WEAVER CIR 70,000 3/19/2001 3. HART 0N655 E WEAVER CIR 40,000 3/19/2001 4. HART 0N655 WEAVER CIRCLE 33,700 6/19/1998 5. POYTH 0N662 W WEAVER CIR 294,690 6/21/2000 6. BLAND 0N670 GREEN PL ...

help with/for pivottable code
Hi everyone! I have code that takes a large workbook and divides it into a number of separate new workbooks based on data that is in column A. What i need is to create code that will create a pivot table in the new workbook. here is my code: Sub Regionalize() Dim wks As Worksheet Dim wksNew As Worksheet Dim wbk As Workbook Dim rng As Range Dim cell As Range Dim lRow As Long Dim sFileName As String Dim sFolder As String Dim sRegion As String Set wks = Sheets("region") Set rng = wks.Range("regiondata") ...

Rebar example code
Can anyone send me a rebar code example. There does not seem to be any examples other than Microsoft documentation. Theres nothing on CodeProject or else where. Many thanks in advance, Aaron On 8 Apr 2007 13:30:14 -0700, "AaronNGray" <aaronngray@gmail.com> wrote: >Can anyone send me a rebar code example. There does not seem to be any >examples other than Microsoft documentation. Theres nothing on >CodeProject or else where. > >Many thanks in advance, > >Aaron CodeProject has that... https://secure.codeproject.com/docking/#ReBars : http://www.codepro...

Replicating Code!!!
Hi there folks, I am currently creating a student achievement spreadsheet and I a using ticks in each cell to state if the student has passed the unit o not. I am using a simple VBA code to have any cell, within a specifie range, ticked upon selecting it. If the cell within the specifie range, already has a tick, the code will remove it. The trick to th code is the use of the letter "a" in a cell that has had it's fon formatted to marlett!! My code: Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub If Not Intersect(Target,...

Code to delete rows not working
Hi, I hope someone can help with this. This is probably really obvious, but I've got the following code held on Sheet 2 of a 3 sheet document. The cells concerned are filled by data from Sheet 1: =Sheet1!A6, for example. I can't see why it wont work. Basically, I want those A-column cells on Sheet 2 which don't hold a value (their corresponding sheet on Sheet 1 is empty) to hide their row. I've tried ascribing a value in the 'If cell.Value=' section. (The cells are formatted for dates. A nil return is giving me 00-Jan-00; I've tried using If cell.Value<01-Jan-0...

Error Code 0x80092026
I keep getting this error when i try and update my XP Pro SP3 machine via windows update. I have deleted the Safer key but i still get this error when trying to update. The PC has not updated for 3 months now and i've tried all the suggestions i can find on here but to no avail. kgbrisc1 wrote: > I keep getting this error when i try and update my XP Pro SP3 > machine via windows update. > > I have deleted the Safer key but i still get this error when trying > to update. The PC has not updated for 3 months now and i've tried > all the suggestions i can...

finance code
I am writing a installment finance program for financing home products. Does anyone know where I can get the formula or code for the "APR" (Annual Percentage Rate) that must be listed on the finance contract. I am have a lot of problem with this. Thanks -- becker Open any code window, and on the menu, chose Help, then type in "Rate". The rate function is what you are looking for. -- Arvin Meyer, MCP, MVP http://www.datastrat.com http://www.mvps.org/access http://www.accessmvp.com "becker" <becker@discussions.microsoft.com> wrote in message news:80A...

Bar Codes
I work at a help desk in a university setting. Teachers are using Excel more and more to create grade books. SOme of them need to format parts of their data into a bar code (items like an ID number). How can I do this? Thanks in advance, Michael mjlucas@stritch.edu Download a bar code font, I always use 3 of 9 ....http://www.barcodesinc.com/free-barcode-font/ On your worksheet format the cell to this barcode font. For it to work properly you must include "*" at the start and end of your data. Start and stop data points. For example in cell A2 enter = "*" & B...

User Form Coding
Hi All Could somebody look at my coding (below) I have a user form that makes appointsments by adding data to a booking sheet. That works fine. But I have also have a command button to open another form to cancel or reshedule the appointments. In order to find a client and the appointment details I use the below code. But I can't seem to get it to work. Any help please. Appoitment worksheet A..........B...........C................D......................E..........F........G.....H custID..Surname..First Name..Contact number..Salon..Date..Time..Treatment Bookings worksheet A..........B......

VBA code (rules) won't work after reboot
First off I am not very knowlegeable about Outook or VBA coding so I apologize in advance for missing the obvious. I have created some rules in outlook (actually exported/imported from a functioning account). The rules basically: -look for an email with an attachment and with a specific word in the subject line -move the email to a different folder -copy the attachment and place it in a shared system folder (done with VBA code) The problem I have is the rules will only work until Outlook is closed down or the server is rebooted. After that the rules partially work (the VBA...

error code 937001
I have Windows Vista and started getting error code 937001 when trying to install updates System Update Readiness Tool for Windows Vista (KB947821) [September 2009] Any suggestions would be appreciated. regards Niyam Right-click on My Computer & select Properties: What Windows version is displayed in the resulting General tab (e.g., Windows Vista Ultimate Service Pack 2)? What anti-virus application or security suite is installed and is your subscription current? What anti-spyware applications (other than Defender)? What third-party firewall (if any)? Were any of...

XML Parse Error Codes
Is there any place I could find a list with all the parsing errors you can get when loading an XML document? I'm mostly interested in error codes generated when using a schema to validate an instance document. All I could find on the web was related to PHP parser implementation, but I'd like to have such a reference specific to MSXML 4.0 SP2 if that's possible. ...