Why do I keep getting error in list box multiple selection

后端 未结 1 1019
执笔经年
执笔经年 2021-01-28 12:21

I am setting up a multi-selection box - using a script I found online, my VBA is pretty much nil. I keep getting next without for error

Private Sub CommandButton         


        
相关标签:
1条回答
  • 2021-01-28 13:09

    The original code from rev 1 better highlights the problem than the current code in the OP:

    Private Sub CommandButton2_Click()
    
    myVAR = ""
    
    For x = 0 To Me.Requirements.ListCount - 1
    If Me.Requirements.Selected(x) Then
    If myVAR = "" Then
    myVAR = Me.Requirements.List(x, 0)
    Else
    myVAR = myVAR & "," & Me.Requirements.List(x, 0)
    End If
    Next x
    
    ThisWorkbook.Sheets("sheet1").Range("v2") = myVAR
    Me.Hide
    
    End Sub
    

    If you're unsure how to correctly and consistenly indent your code, you can use an indenter tool, and then you can simply follow the indentation levels:

    For x = 0 To Me.Requirements.ListCount - 1
    |   If Me.Requirements.Selected(x) Then
    |   |   If myVAR = "" Then
    |   |   |   myVAR = Me.Requirements.List(x, 0)
    |   |   Else
    |   |   |   myVAR = myVAR & "," & Me.Requirements.List(x, 0)
    |   |   End If
    |   Next x '<~ not lined up!
    *woopsie*
    

    Referring to the code as it appears in the current revision, the inner If...Else block isn't terminated, so the compiler is taking the outer End If in its place, and then runs into Next when it expects End If - hence the "next without for" compile error.

    The correct code would be:

    For x = 0 To Me.Requirements.ListCount - 1
    |   If Me.Requirements.Selected(x) Then
    |   |   If myVAR = "" Then
    |   |   |   myVAR = Me.Requirements.List(x, 0)
    |   |   Else
    |   |   |   myVAR = myVAR & "," & Me.Requirements.List(x, 0)
    |   |   End If
    |   End If
    Next x
    
    0 讨论(0)
提交回复
热议问题