菜鸟在这里。我在这个网站上找到了很多代码,并想对所有贡献的人表示感谢。
我的问题是我有一个用户窗体。我单击一个按钮以调出一个 InputBox,他们在其中输入一个值以搜索银行名称、银行家名称、公司名称等。
我有代码来做搜索没问题,但我希望能够继续搜索 InputBox 值的所有实例。例如,搜索名称“Smith”,如果第一个不是我需要的,则继续搜索,直到找到我正在寻找的那个。
Dim ws As Worksheet
Dim rFound As Range
Dim strName As String
On Error Resume Next
strName = InputBox("Please Enter Search Value." & vbNewLine & "Entry Must Be Exact Cell Value!", "Search Value")
If strName = "" Then Exit Sub
For Each ws In Worksheets
With ws.UsedRange
Set rFound = .Find(What:=strName, After:=.Cells(1, 1), LookIn:=xlValues, LookAt:=xlPart)
If Not rFound Is Nothing Then
firstaddress = rFound.Address
Application.Goto rFound, True
Exit Sub
End If
End With
Next ws
On Error GoTo 0
MsgBox "Merchant not found. Please make sure you typed it correctly.", vbOKOnly + vbCritical, "Invalid Entry"
最佳答案
您需要修改您的搜索,以便您的代码“记住”它停止的位置,如下所示:
Option Explicit
Dim ws As Worksheet
Dim rFound As Range
Dim strName As String
Static First as Range
'On Error Resume Next
if First is Nothing Then 'we haven't found anything yet
Set First = Worksheets(1).Cells(1,1) 'start searching at the beginning
End If
strName = InputBox("Please Enter Search Value." & vbNewLine & "Entry Must Be Exact Cell Value!", "Search Value")
If strName = "" Then Exit Sub
For Each ws In Worksheets
With ws.UsedRange
Set rFound = .Find(What:=strName, After:=First, LookIn:=xlValues, LookAt:=xlPart)
while Not rFound Is Nothing
if first is nothing then
First = rFound 'store off this address for use in our next search
end if
if first <> rFound Then 'we've found a NEW instance of the search item
firstaddress = rFound.Address
Application.Goto rFound, True
MsgBox "Found one!"
Set rFound = .Find(What:=strName, After:=rFound, LookIn:=xlValues, LookAt:=xlPart)
else 'we're back at the start, so jump out of the loop
set rFound = Nothing
End If
wEnd
End With
Next ws
On Error GoTo 0
MsgBox "Merchant not found. Please make sure you typed it correctly.", vbOKOnly + vbCritical, "Invalid Entry"
几点:
Option Explicit
这意味着您的代码现在不会运行,因为您从未声明 firstaddress
.从功能区启用该选项对您的理智至关重要:工具 |选项 |编辑然后检查 Require Variable Declaration
First
作为 Static
,它将在对您的搜索例程的调用之间保持设置。那样的话,既然我们在喂First
进入.Find()
函数,它将从中断的地方继续搜索。 set First = Worksheets(1).Cells(1,1)
On Error Resume Next
在 中很有用非常有限的情况。这不是其中之一。它允许您忽略代码中的错误,以便您可以立即处理它,这不是您在这种情况下想要的。跟进On Error Goto 0
,它重新启用默认错误处理实际上永远不会超过 1 行代码 - 而不是整个子例程。 关于vba - 在整个 Workbook 中的 InputBox 中查找下一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657995/