我是VBA excel的新手,我希望有一个搜索系统,当我要在特定单元格中输入值时,将在单元格范围内搜索该值。宏必须转到第一个单元格,然后选择下一个单元格,直到找不到匹配项。我有一个代码,我通过网络搜索,但我很难想出来。
感谢您的帮助! :)
Sub FindADrug()
Dim DrugCell As Range
Dim SearchRange As Range
Dim SearchCell As String
Dim FirstDrugCell As String
SearchCell = Sheets("Sheet1").Range("D6").Value
Set SearchRange = Range("A1:A335")
Set DrugCell = SearchRange.Find(What:=SearchCell, MatchCase:=False, LookAt:=xlPart)
If Not DrugCell Is Nothing Then
DrugeCell.Select
Else
FirstDrugCell = DrugCell.Address
Do
Set DrugCell = SearchRange.FindNext(DrugCell)
Loop While DrugCell.Address <> FirstDrugCell
End If
End Sub
答案 0 :(得分:0)
请你试试以下吗?
我对您的代码做了一些小改动。
首先我定义了一个名字&#34; Drug
&#34;它指的是D6
上的单元格Sheet 1
。这样,如果您决定移动搜索单元,则无需更新VBA代码。
其次它现在正在使用一个单元格,您必须将其设置为已定义的名称&#34; placeholder
&#34;存储找到的最后一个条目的行号。这样,下次运行时,它将转到下一个条目(如果有的话)。如果再次运行它到达最后一场比赛,它将显示一个消息框,告知没有其他比赛。同时&#34; placeholder
&#34;的价值重置为1
,以便您可以重新开始搜索。
当您更改单元格D6
的值时,该值也会重置为1(请参阅Worksheet_Change
子例程)。
Sub FindADrug()
Dim DrugCell As Range
Dim SearchRange As Range
Dim SearchCell As String
Dim FirstDrugCell As String
Dim Counter As Integer
Counter = WorksheetFunction.CountA(Range("A:A"))
SearchCell = Range("Drug").Value
Set SearchRange = Range("A1:A" & Counter)
'Range("placeholder") refers to a defined name which is used to store the row of the last drug found.
'You have to set it before using the macro.
Set DrugCell = SearchRange.Find(What:=SearchCell, After:=Cells(Range("placeholder"), 1), MatchCase:=False, SearchDirection:=xlNext, LookAt:=xlPart)
If DrugCell Is Nothing Then
MsgBox "No drug found.", vbOKOnly, "No results..."
Else
FirstDrugCell = DrugCell.Address
If DrugCell.Row < Range("placeholder").Value Then
MsgBox "Last drug found", vbOKOnly, "Last drug"
Range("placeholder") = 1
Else
Range("placeholder") = DrugCell.Row
DrugCell.Select
Set DrugCell = SearchRange.FindNext(DrugCell)
End If
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row = 6 And Target.Column = 4 Then Range("placeholder") = 1
End Sub
我希望我能正确理解这个问题。拜托,你能告诉我这是否能解决你的问题吗?