2016-04-14 8 views
1

私はBPName2SPName2という2つのテキストボックスを持つuserformを持っています。以下のコードのIf found=true then exit forステートメントの後。 2番目のテキストボックスに移動したいと思います。しかし、そうすることに問題があります。誰でもこれを行う方法についてのアイデアはありますか?1つのテキストボックスの終了イベントから他のテキストボックスへのカーソルのフォーカスを設定する方法

Private Sub txt_BPName2_Exit(ByVal Cancel As ReturnBoolean) 

Dim Row As Integer 
    Row = ActiveCell.Row 
    Dim c As Range 
    Dim found As Boolean 


    found = False 
    For Each c In Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row) 
     If c.Value = txt_BPName2 Then MsgBox "Cell " & c.Address & " Base Product Found." 
     If c.Value = txt_BPName2 Then found = True 
    If found = True Then Exit For 

    Next 

    If found = False Then 
     'Cells(Row, 1).Value = txt_BPName2.Text 
     MsgBox ("Base Product not found") 
     'ActiveCell.Offset(1, 0).Select 
     Add_Inventory_SP.Hide 
    End If 

    Cancel = True 
End Sub 
+1

このコード行の後に正確に何をしたいですか? –

+0

'MsgBox'で行をコメントアウトします。それはあなたが望むことをしますか? –

+1

'NextTextBoxName.SetFocus'に似ていますか?また、コードをより効率的に変更することもできます。 – PatricK

答えて

2

もの

  1. のカップルは、Excelの行で作業しているときはいつでも、Integerの代わりにLongを使用してください。ポストExcel 2007では、行の数は、あなたがブール変数

  2. は完全にあなたのオブジェクトを修飾する必要はありません整数

  3. を扱うことができない1048576まで行っています。 Activecellは避けてください。表示することがありますthis

  4. 予約語を変数名として使用しないでください。 は予約語です。

これはあなたの試みですか? (未テスト

Private Sub txt_BPName2_Exit(ByVal Cancel As ReturnBoolean) 
    Dim ws As Worksheet 
    Dim lRow As Long 
    Dim c As Range, rng As Range 

    Set ws = ThisWorkbook.Sheets("Sheet1") '<~~ Change as applicable 

    With ws 
     lRow = .Range("A" & .Rows.Count).End(xlUp).Row 

     Set rng = .Range("A2:A" & lRow) 
    End With 

    For Each c In rng 
     If c.Value = txt_BPName2 Then 
      MsgBox "Cell " & c.Address & " Base Product Found." 

      SPName2.SetFocus 
      Exit Sub 
     End If 
    Next 

    MsgBox ("Base Product not found") 
    Add_Inventory_SP.Hide 
    Cancel = True 
End Sub 

:ルーピング及び探索の代わりに、より効率的なアプローチは、範囲内の名前を検索する.Find又はApplication.Worksheetfunction.CountIfを使用することであろう。 .Findに興味があればThis

+0

@ Siddharth Rout-ありがとう!あなたのアプローチははるかに良いです。 – Abhi0609

関連する問題