2016-04-22 67 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. 
相關問題