Easy answers for anyone

M

m5u4r3p2h1y

Good afternoon, I am very new to VBA and was hoping if anyone code tel
me why the following code only loops once. (I am just testing some stuf
out in it). The message boxes are to see how many time it loops, bu
they both respond with 1.

Sub ref()

Dim RefNum(0 To 9) As String
Dim RefFound As Range
Dim wk As Workbook
Dim i, count As Integer


RefNum(0) = "100617"
RefNum(1) = "100203"
RefNum(2) = "105522"
RefNum(3) = "105774"
RefNum(4) = "105199"
RefNum(5) = "100514"
RefNum(6) = "105207"
RefNum(7) = "107065"
RefNum(8) = "101957"
RefNum(9) = "101394"

count = 0

Set wk = Workbooks.Open(ThisWorkbook.Path & "\2005 Hourly by Re
cleaned.xlsx")
wk.Sheets("Hourly").Activate

For i = 0 To i = 9

Set RefFound = Cells.Find(What:=RefNum(i), After:=ActiveCell
LookIn:=xlValues, LookAt _
:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext
MatchCase:= _
False, SearchFormat:=False)
count = count + 1
Next
MsgBox (count)
MsgBox (i)
End Sub


Thanks in advance for answer
 
J

joeu2004

m5u4r3p2h1y said:
was hoping if anyone code tell me why the following code
only loops once. [....]
Dim i, count As Integer [....]
For i = 0 To i = 9

The For statement should be:

For i = 0 to 9

As you wrote, it is parsed as:

For i = 0 to (i = 9)

"i = 9" returns True (-1) or False (0). Since i=0 initially, "i = 9" is
False (0). So your For statement is effectively:

For i = 0 to 0

which will indeed loop only once.

By the way, you Dim statement should probably be at least:

Dim i As Integer, count As Integer

As you wrote it, i is Variant. I suspect that was not your intent.

Also, there is little point in using Integer type, unless you have very huge
arrays. You should use Long to be flexible. There is no performance cost
in modern computers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top