2016-04-22 69 views
-1

我有一个带有几个文本框的用户表单,并且需要点击表单上最后一个命令按钮来验证数据。代码是:如何在出现错误消息后将焦点设置回文本框。

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 

Exit sub将光标放回到文本框中。但是,我有其他的代码行需要在退出子行下面进行。所以,我不想退出sub。有没有替代退出子?或者我可以突破并再次进入子队?

+0

这是不是VB.NET,它不是VBA,它不是VBScript和它是不是宏;所以这些标签都是不相关的。它是VB6代码 – Plutonix

+0

对于它的价值,“Exit Sub”不会将光标置于文本框中,“txt_SPName1.SetFocus”会将curson放入文本框中。 “Exit Sub”停止运行代码。顺便说一句,如果您使用find函数而不是遍历每条记录来查看是否有重复项,那么此代码将更清晰高效。我会留给你去研究和实施。 – OpiesDad

+0

@Plutonix我认为这是VBA,但你是正确的,大多数标签都是不相关的。 – OpiesDad

回答

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. 
相关问题