Solved

I need help with a simple excel vba loop

Posted on 2013-05-15
3
234 Views
Last Modified: 2013-05-15
Hello All,

Why doesn't this stop in cell A15?
Any help appreciated!

Thanks.
Sub StopatFifteen()
Dim aktKolli As Long
Dim kolliAntal As Long

kolliAntal = 15
aktKolli = 0

Do While aktKolli < kolliAntal
    
    For Each cell In ActiveSheet.Range("A1:A50")
        aktKolli = aktKolli + 1
        cell.Value = aktKolli
    Next cell
Loop
    
End Sub

Open in new window

0
Comment
Question by:Ot_Gu
  • 2
3 Comments
 
LVL 22

Expert Comment

by:rspahitz
ID: 39168784
Why doesn't it stop?
Because your loop condition is outside your For loop, so the for loop does all 50 cells before checking for the next value.
0
 
LVL 22

Accepted Solution

by:
rspahitz earned 500 total points
ID: 39168793
Maybe what you want is something more like this?

    For Each cell In ActiveSheet.Range("A1:A50")
        aktKolli = aktKolli + 1
      If aktKolli <= kolliAntal Then
           cell.Value = aktKolli
      Else
         Exit For
      End If
    Next cell

Open in new window

0
 

Author Closing Comment

by:Ot_Gu
ID: 39170408
That is what I wanted. Thanks you very much.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
This article descibes how to create a connection between Excel and SAP and how to move data from Excel to SAP or the other way around.
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now