如何在出现错误消息后将焦点设置回文本框。

时间:2016-04-22 19:19:12

标签: vba excel-vba excel

我有一个包含多个文本框的用户表单,需要在单击表单上的最后一个命令按钮时验证数据。代码是:

Private Sub CmdSave1_Click()

 Dim row As Long
  Dim c As Range
 row = ActiveCell.row


  For Each c In Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).row)
     If c.Value = txt_BPName1 Then
        MsgBox " Duplicate Found.Please enter unique Base Product"
        txt_BPName1.SetFocus  '>>> the cursor does not return textbox here.
              'txt_SPName1.SetFocus
                End If
                Next
                'txt_SPName1.SetFocus
                'Exit Sub
     For Each c In Range("B2:B" & Cells(Rows.Count, 1).End(xlUp).row)
         If c.Value = txt_SPName1 Then
           MsgBox "Cell " & c.Address & " Duplicate sub Product Found."
              txt_SPName1.SetFocus
              End If
              Next
              'txt_loc1.SetFocus
              'Exit Sub

退出子将光标放回文本框。但是,我还需要在退出子行下面执行其他代码行。所以,我不想退出sub。是否有替代退出子?或者我可以突然再次进入潜艇吗?

1 个答案:

答案 0 :(得分:0)

您可以使用“GoTo”声明:

For Each c In Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).row)
      If c.Value = txt_BPName1 Then
         MsgBox " Duplicate Found.Please enter unique Base Product"
         txt_BPName1.SetFocus  '>>> the cursor does not return textbox here.
         'txt_SPName1.SetFocus
      GoTo DuplicateFound
      End If
 Next

 ....rest of code

 DuplicateFound:
      ....code you want to happen if a duplicate is found.