如何将光标的焦点从一个文本框的退出事件设置到另一个文本框

时间:2016-04-14 02:31:57

标签: vba excel-vba excel

我有一个包含两个文本框BPName2SPName2的用户表单。在下面的代码中的If found=true then exit for语句之后。我想转到第二个文本框。但是,这样做有困难。任何人都知道如何做到这一点?

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 :(得分:2)

一些事情

  1. 每当您使用Excel Rows时,请使用Long代替Integer。发布Excel 2007后,行数已达到1048576,整数无法处理

  2. 您不需要布尔变量

  3. 完全限定对象。避免使用Activecell。您可能希望查看this

  4. 避免将保留字用作变量名。 Row是保留字。

  5. 这是你在尝试什么? (的未测试

    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
    

    注意:代替循环和搜索的更有效方法是使用.FindApplication.Worksheetfunction.CountIf来搜索范围中的名称。如果您对.Find感兴趣,那么您可以看到This