Thread: if then loop
View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
S. I. Becker S. I. Becker is offline
external usenet poster
 
Posts: 15
Default if then loop


wrote in message
oups.com...
I don't understand why this code works:

Private Sub one_Click()
For i = 27 To 999
Cells(i, i).Value = i
If Cells(i, 1).Value = "More" Then
Cells(i, 1).Value = Sheets("Prices").Range("A3")
Cells(i, 3).Value = Sheets("Prices").Range("B3")
Cells(i, 4).Value = Sheets("Prices").Range("C3")
Exit For
End If
Next i
End Sub

But this code does not:

Private Sub CommandButton6_Click()
For i = 31 To 999
Cells(i, i).Value = i <<<<<<HERE IS WHERE IT STOPS

If Cells(i, 2).Value = "Fruit" Then
Range("AD12").Select
Application.CutCopyMode = False
Selection.Copy
Range ("i, 2"). Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
Exit For
End If
Next i

Range("AA1:AD10").Select
Application.CutCopyMode = False
Selection.ClearContents
Range("B30").Select
End Sub

What is confusing is the same line of code works in the fist example
but does not in the second.

Any help is most welcome. In the second example I am searching for a
certain value in the next row with value FRUIT in col B, when I find
that cell, copy the value of another cell into that cell, clear a
certain range so I can begin again.


The line "Cells(i, i).Value = i" will fail when i 256. In the one_Click
Sub, I am guessing that the Exit For is called before i gets to 256, i.e the
first occurrence of "More" is in a row less then 257. I also think that you
are unlikely to intend that the numbers 27 to 999 (or 31 to 999) are output
diagonally through your worksheet. You probably want Cells(i, x).Value = i
in there instead. Change x to be the appropriate column number.

Also, in the way you are testing, "FRUIT" is different from "Fruit", and
"MORE" is different from "More", consider instead:

If UCase$(Cells(i, 2).Value) = "FRUIT" Then

to be case insensitive.

Stewart