开发者

In nested Excel VBA For...Next loop, parent Next cannot find its For

For j = 0 to SpreadCount
    If TypeName(ChainsDC(j,0) = "String" 'testing for an error
        Goto EndLoop
    Else:
        For i = 0 to RscSct
            ...do amazing things here (no loops)
        Next i
EndLoop:
Next j 开发者_如何学JAVA'<<<PROBLEM

Compiler complains Next j (line 9) is a "Next without For".


Your IF statement is the problem. You need to add both a Then and a End If:

For j = 0 to SpreadCount
    If TypeName(ChainsDC(j,0) = "String" **Then**
        Goto EndLoop
    Else:
        For i = 0 to RscSct
            ...do amazing things here (no loops)
        Next i
    **End If**
EndLoop:
Next j '<<<PROBLEM

Edit
Your Typename is also missing a close parenthesis.


For j = 0 to SpreadCount
    If TypeName(ChainsDC(j,0)) <> "String" Then
        For i = 0 to RscSct
            ...do amazing things here (no loops)
        Next i
    End If
Next j

As Remou pointed out, you should get rid of the Goto and test what you want to test, namely that it's not a string.

You should generally never have a colon after else unless there's another executable piece of code on that line. And even then...


There are several things wrong with your code and logic.

For j = 0 to SpreadCount
    If TypeName(ChainsDC(j,0) = "String" 'testing for an error
        Goto EndLoop
    Else:
        For i = 0 to RscSct
            ...do amazing things here (no loops)
        Next i
EndLoop:
Next j '<<<PROBLEM

The major issue is the logic - if you only care if the TypeName is not a string, check for that. There is no need to add the else statement, let alone a GoTo. As it's often said:

A GoTo statement can often indicate an opportunity to fix the logic in your code

One thing that helps is to concentrate on what you want to do, not what you don't want to do. Writing the expected/desired path first, then adding in side cases after (if needed) is good practice.

Other areas to fix:

  • In line 2, you are missing a )
  • In line 2, take out the comment. Code is/should be self-explanatory.
  • You should reverse i and j. Someone reading the code will assume i comes first.
  • In line 4, you should remove the ":"

Here is the code cleaned up:

For i = 0 To SpreadCount
    If TypeName(ChainsDC(i, 0)) <> "String" Then
        For j = 0 To RscSct
            '...do amazing things here
        Next
    End If
Next


Your Else: may be the problem, as well as the missing End If.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜