我尝试设置搜索框以在多个工作表中查找值。
如果可以找到值,它将显示工作表中的列。然后单击“确定”继续在下一个工作表中搜索,或单击“取消”退出搜索。我相信这部分正在发挥作用。
然而,当找不到值时,我希望它可以搜索每个工作表并在搜索结束时返回消息框“Not found”。我无法找到正确的方法,并将错误消息显示为“Next without For”。
如果可能的话,请你看一下并更正“未找到”部分(在Else之后)?
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim Search As String
Search = TextBox1.Text
For Each ws In ThisWorkbook.Worksheets
Dim r As Range
Dim f1 As Range
If ws.Name = "SELECTOR" Then GoTo nws
Set r = ws.Cells.Find(What:=Search, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) 'finds first match
If Not r Is Nothing Then
Application.Goto (Sheets(ws.Name).Range(r.Address))
If MsgBox("found on " & ws.Name, vbOKCancel) = vbCancel Then
Exit Sub
End If
Set f1 = r
Do While Not r Is Nothing
Set r = ws.Cells.FindNext(r)
If f1.Address = r.Address Then GoTo nws
Application.Goto (Sheets(ws.Name).Range(r.Address))
If MsgBox("found on " & ws.Name, vbOKCancel) = vbCancel Then
Exit Sub
End If
Loop
Else
If MsgBox("not found on " & ws.Name, vbOKCancel) = vbCancel Then
Exit Sub
End If
nws:
Set r1 = Nothing
Next ws
End Sub
答案 0 :(得分:0)
如果您使用一致的代码缩进,您会发现缺少End If
。这会使编译器感到困惑,因为它会在适当的缩进级别上遇到Next ws
并且没有For
来匹配它:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim Search As String
Search = TextBox1.Text
For Each ws In ThisWorkbook.Worksheets
Dim r As Range
Dim f1 As Range
If ws.Name = "SELECTOR" Then GoTo nws
Set r = ws.Cells.Find(What:=Search, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) 'finds first match
If Not r Is Nothing Then
Application.Goto (Sheets(ws.Name).Range(r.Address))
If MsgBox("found on " & ws.Name, vbOKCancel) = vbCancel Then
Exit Sub
End If
Set f1 = r
Do While Not r Is Nothing
Set r = ws.Cells.FindNext(r)
If f1.Address = r.Address Then GoTo nws
Application.Goto (Sheets(ws.Name).Range(r.Address))
If MsgBox("found on " & ws.Name, vbOKCancel) = vbCancel Then
Exit Sub
End If
Loop
Else
If MsgBox("not found on " & ws.Name, vbOKCancel) = vbCancel Then
Exit Sub
End If
nws:
Set r1 = Nothing
Next ws '<-- This has no matching For, but really you are missing an End If
' (Probably meant to be an End If just before your nws label
' in order to close your If Not r Is Nothing Then statement)
End Sub
我的最佳猜测&#34;至于你想要的地方End If
(基于GoTo nws
之前If
的{{1}}缺少End If
)就在{{1}之前标签,从而成为代码的最后一部分:
nws:
注意:
您有一个 Else
If MsgBox("not found on " & ws.Name, vbOKCancel) = vbCancel Then
Exit Sub
End If
End If
nws:
Set r1 = Nothing
Next ws
End Sub
语句,但您从未在其他地方声明或使用变量Set r1 = Nothing
。
您两次使用的r1
语句相当于Application.Goto (Sheets(ws.Name).Range(r.Address))
。我相信你想使用Application.Goto Sheets(ws.Name).Range(r.Address).Value
(即没有括号),可以简化为Application.Goto Sheets(ws.Name).Range(r.Address)
。