我試圖設置一個搜索框來查找多個工作表中的值。在多個工作表中搜索值與下一個沒有對於錯誤
如果可以找到值,它將顯示工作表中的列。然後點擊確定繼續在下一個工作表中進行搜索,或點擊取消退出搜索。我相信這部分工作。
但是,當找不到值時,我希望它可以搜索每個工作表並在搜索結束時返回消息框「未找到」。我無法制定出正確的方法,並顯示錯誤消息爲「Next for 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
嗨YowE3k,我有End If之前nws標籤。你的意思是我需要添加另一個End If?非常感謝 –
@JDing當前'End If'正在關閉'If MsgBox(「在&ws.Name,vbOKCancel)= vbCancel Then'語句中找不到。您需要額外的一個關閉「If Not Is Nothing Then」語句。如果在縮進代碼時向下查看代碼,則會看到「If Not r Is Nothing Then」和「Else」都以相同的縮進開始,但沒有「End If」以相同的縮進級別開始。 – YowE3K
@JDing我還會在這裏爲[Rubberduck](http://rubberduckvba.com)(這是一個開源的VBIDE插件項目[其中一個其他高代表VBA答覆者](https:/ /stackoverflow.com/users/1188513/mats-mug)管理)。使用它可以幫助你縮減代碼,並有助於防止這些問題。 – YowE3K