Even after posting your code your question is still not clear, so I will explain some basic stuff and see if that helps you.
For/Next first:
Using For...Next statements (VBA) | Microsoft Docs[
^]
Everything after the
For
... will be repeated up to the
matching Next
You can have anything in that repeated statement block that is a valid statement - and that includes other For/Next loops, If statements, virtually anything that is a valid statement -
Writing Visual Basic statements (VBA) | Microsoft Docs[
^]. When you have For-loops inside for-loops, it is known as "nested for loops" or "nesting"
It is not compulsory to include the counter variable name after Next , but it can help your code be more readable if you have a lot of For-loops, especially if they are nested.
What you
cannot do is mix up the order of the next statements e.g. This is not legal code
For Loop1 = 0 to 50
For Loop2 = 0 to Loop1
Next Loop1
Next Loop2
The Inner Loop must be completed before the Outer Loop. Indenting your code helps make this more obvious too
For Loop1 = 0 to 50
For Loop2 = 0 to Loop1
Next Loop2
Next Loop1
You can re-use the same counter variable as many times as you like, as long as you don't try to re-use it in the same set of nested loops e.g. This is legal
For Loop1 = 0 to 50
Next Loop1
For Loop1 = 17 to 34
Next Loop1
But this is NOT
For Loop1 = 0 to 50
For Loop1 = 17 to 34
Next Loop1
Next Loop1
If-statements:
Using If...Then...Else statements (VBA) | Microsoft Docs[
^]
Just like the "boundaries" of For-loops are defined by the words
For
and
Next
with everything in-between being repeated that number of times, an If-statement is bounded by the words
If
and
End If
. It's a little more complicated because you can break If-statements up into sections using
Else
or
ElseIf
but the principals still apply - and indentation will help you read your code. You can have any sort of statement in the block between
-
If
and
ElseIf
or
-
If
and
Else
or
-
Else
and
End If
or
-
If
and
Else
or
-
If
and
End If
If you want to use loops in those statement blocks, then you can. You can even use the same Loop counter - but the loop must be fully enclosed by the statement block. I.e. This is legal
If myTest = myComparison Then
For loop1 = 0 to 50
Next loop1
Else
For loop1 = 50 to 100
Next loop1
End If
But this is NOT
If myTest = myComparison Then
For loop1 = 0 to 50
Else
Next loop1
End If
A couple of other points - I copied your code to compile it to see if there were issues (Compile is on the Debug Menu in the VBA Editor) and it wouldn't. Not because there were any issues with your nesting of Ifs and Fors but because you hadn't declared some variables. I had to add
Dim nrows As Long, element As Long, currentmoving As Long, signal As Long, replace_this_line As Boolean
There are a lot of things you haven't initialised with values as well. Plus
data
,
lag
,
threshold
and
weights
should all really be given types instead of defaulting to Variant type.