1

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
5
  • 8
    For p = 1 To length Commented Jul 12, 2016 at 19:31
  • Since you already know how to work with arrays, why not put the values in Column AE into an array and cycle through that instead? It would be quicker then looping the cells themselves. AEArray = Worksheets("sheet1").Range("AE3:AE" & length).Value then do another for loop on this array instead. Commented Jul 12, 2016 at 19:35
  • Your answer fixed it. And great suggestion! this is only my 2nd day of using VBA so any advice is appreciated. Commented Jul 12, 2016 at 19:48
  • Sorry, @ScottCraner - your comment didn't even register, or I'd have told you to make it an answer so you could get your magical internet points... Commented Jul 12, 2016 at 20:08
  • 1
    @FreeMan too lazy today. Commented Jul 12, 2016 at 20:19

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.