Search code examples
arraysvbafor-loopnested-loops

VBA nested for loop won't Run


Hi I'm working on a macro in VBA for excel. I have a nested for loop in my code as seen below. The second loop does not run; even a MsgBox() command within the second loop doesn't result in any action and the program just seems to skip over the nested loop with no reported errors.

In plain English this nested loop should:

1) Take the string from the i entry in the array categories_string (first for loop).

2) iterate through the 300+ rows in column "AE" in the excel file (second for loop, "length" is the length of the column of data in "AE")

3) look for string matches and add 1 to the corresponding entry in the categories_value array which is populated with variables set to 0 (the if statement).

For i = LBound(categories_string) To UBound(categories_string)
   For p = 1 To p = length
      If Worksheets("sheet1").Cells(p + 2, "AE").Value = categories_string(i) Then
        categories_value(i) = categories_value(i) + 1
      End If
   Next
Next

Solution

  • Change

       For p = 1 To p = length
    

    to

       For p = 1 To length
    

    Should fix you right up.

    You may want to consider Scott Cranner's comment as well, especially if your categories_string is large and length is large. Or, just do it for the practice