Solved

I need help with a simple excel vba loop

Posted on 2013-05-15
3
224 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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
This article will guide you to convert a grid from a picture into Excel format using Microsoft OneNote and no other 3rd party application.
This Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.
This Micro Tutorial demonstrates in Microsoft Excel how to consolidate your marketing data by creating an interactive charts using form controls. This creates cool drop-downs for viewers of your chart to choose from.

747 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

13 Experts available now in Live!

Get 1:1 Help Now