Home > Enterprise >  For Each Loop giving error (Next without For)
For Each Loop giving error (Next without For)

Time:01-07

Heading_Value = "L"

For Each cell In Range(Heading_Start, Heading_End)
    
    cell.Value = Heading_Value
    
    If Heading_Value = "L" Then
        Heading_Value = "R"
        If Heading_Value = "R" Then
            Heading_Value = "Total"
        Else
            Heading_Value = "L"
        End If
Next cell

the 2 variables in the range correspond to cell addresses for example "Heading Start" = Range "A5"

not sure why this is saying next without for im guessing I did something wrong with the Nested If Statements

basically its supposed to go through a range (Lets say Row 1 Columns A:F

should look like

A B C D E F
T R Total T R Total

CodePudding user response:

You're missing End If closing outer If Heading_Value = "L" Then

        Else
            Heading_Value = "L"
        End If
    End If  <-- here
Next cell

CodePudding user response:

Found a workaround

Heading_Value = 1

For Each cell In Range(Heading_Start, Heading_End)
    
    cell.Value = "H" & Heading_Value
    
    If Heading_Value = 3 Then
        Heading_Value = 0
    End If
    
    Heading_Value = Heading_Value   1
    
Next cell

With Range(Heading_Start, Heading_End)
    .Replace what:="H1", Replacement:="L"
    .Replace what:="H2", Replacement:="R"
    .Replace what:="H3", Replacement:="Total"
End With
  • Related