Next without for error userform Excel VBA error with Else-If Statement

Next without for error userform Excel VBA error with Else-If Statement

我收到一个我不明白的“Next without For”错误。

我有一个带有 2 个文本框和 1 个组合框的用户窗体:

当我点击提交按钮时,我想检查序列号是否与第4列中的现有数据匹配。在这种情况下,我希望数据填写处理列(右侧 3 行)带有来自 ComboBox1 的文本。

如果匹配,我想填充一个全新的行。

如果没有输入配置,我想退出子或消息框。哪个都可以。

我尝试重新排列 IfElseForNext,但似乎没有任何效果。

  Private Sub SubmitButton_Click()

  Dim serial_ID As String
  serial_ID = Trim(SN_TextBox1.Text)
  DispValue = ComboBox1.Value

  Worksheets("RMA Tracker").Activate
  lastrow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row

  For i = 2 To lastrow
 

   'Searches for matching RMA & SN 'this assigns data to Log Sheet, if the data is brand new

        If Worksheets("Sheet1").Cells(i, 4).Value <> serial_ID Then
           ActiveSheet.Cells(i + 1, 1) = RMA_TextBox1.Value
           ActiveSheet.Cells(i + 1, 4) = SN_TextBox1.Value
           ActiveSheet.Cells(i + 1, 7) = ComboBox1.Value


        Else
    
   'this assigns data to disposition column to matching entries in serial number column

         If Worksheets("Sheet1").Cells(i, 4).Value = serial_ID Then
         ComboBox1.Text = Worksheets("Sheet1").Cells(i, 7).Value


         Else
   
   
         If DispValue = "" Then
         Exit Sub
  

         End If

 Next i

 'this clears the fields of userform when button is clicked and saves it automatically
 ActiveWorkbook.Save
 Call resetform


  End Sub

错误信息有点误导。问题是您的 If 语句。您有三个 If 语句,但只有一个 End If 语句。由于您还有两个 Else 语句,我假设您需要一个 If / ElseIf 结构。有两种方法可以解决这个问题。

  1. 三个独立的IF语句(三个语句都会被执行)

             If Worksheets("Sheet1").Cells(i, 4).Value <> serial_ID Then
                ActiveSheet.Cells(i + 1, 1) = RMA_TextBox1.Value
                ActiveSheet.Cells(i + 1, 4) = SN_TextBox1.Value
                ActiveSheet.Cells(i + 1, 7) = ComboBox1.Value
             End if
    
        'this assigns data to disposition column to matching entries in serial number column
    
              If Worksheets("Sheet1").Cells(i, 4).Value = serial_ID Then
                  ComboBox1.Text = Worksheets("Sheet1").Cells(i, 7).Value
              End if
    
              If DispValue = "" Then
                 Exit Sub
              End If
    
  2. 或者,你可以设置一个If/ElseIf结构(如果first/secondIf语句是True,随后的 If 语句将不会到达,代码执行将在 End If 语句之后继续 - 除非你到达 Exit Sub 当然):

              If Worksheets("Sheet1").Cells(i, 4).Value <> serial_ID Then
                  ActiveSheet.Cells(i + 1, 1) = RMA_TextBox1.Value
                  ActiveSheet.Cells(i + 1, 4) = SN_TextBox1.Value
                  ActiveSheet.Cells(i + 1, 7) = ComboBox1.Value
              ElseIf Worksheets("Sheet1").Cells(i, 4).Value = serial_ID Then
                  ComboBox1.Text = Worksheets("Sheet1").Cells(i, 7).Value
              ElseIf DispValue = "" Then
                 Exit Sub
              End If