我有一个包含两个文本框BPName2
和SPName2
的用户表单。在下面的代码中的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
答案 0 :(得分:2)
一些事情
每当您使用Excel Rows时,请使用Long
代替Integer
。发布Excel 2007后,行数已达到1048576,整数无法处理
您不需要布尔变量
完全限定对象。避免使用Activecell
。您可能希望查看this
避免将保留字用作变量名。 Row
是保留字。
这是你在尝试什么? (的未测试强>)
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