Excel VBA – 循环遍历一列单元格,并search工作簿中的每个单元格值

我需要创build一个macros,通过包含string的选定单元格的列表进行循环,并获取每个string并在整个工作簿中search该string。 如果findstring,则子应该退出,并且应该selectfind的string,否则将移动到下一个要find的string,直到列表结束。

当我运行我的代码时,sub不会退出,当列表中的string被find,它不会去那个单元格。

Option Explicit Dim sheetCount As Integer Dim datatoFind Sub Button1_Click() Find_File End Sub Private Sub Find_File() Dim c As Range Dim counter As Integer Dim currentSheet As Integer Dim notFound As Boolean notFound = True For Each c In Selection.Cells On Error Resume Next currentSheet = ActiveSheet.Index datatoFind = StrConv(c.Value, vbLowerCase) If datatoFind = "" Then Exit Sub sheetCount = ActiveWorkbook.Sheets.Count If IsError(CDbl(datatoFind)) = False Then datatoFind = CDbl(datatoFind) For counter = 1 To sheetCount Sheets(counter).Activate Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlValues, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate If InStr(1, StrConv(ActiveCell.Value, vbLowerCase), datatoFind) Then notFound = False Sheets(counter).Activate Range("datatoFind").Select Exit For End If Next counter If notFound = True Then MsgBox ("Value not found") Sheets(counter).Activate Else Exit Sub End If Next c End Sub 

任何帮助深表感谢!

如果是我的代码,我会做出不同的,但只是不改变你的代码戏剧性

 Public Sub Find_File() Dim c As Range Dim counter As Integer Dim currentSheet As Integer Dim notFound As Boolean Dim datatoFind As String Dim sheetCount As Integer Dim cellFound As Range Dim cellToFind As Range Dim originalSheet As Worksheet notFound = True Set originalSheet = ActiveSheet For Each c In Selection.Cells On Error Resume Next currentSheet = ActiveSheet.Index Set cellToFind = c datatoFind = StrConv(c.Value, vbLowerCase) If datatoFind = "" Then Exit Sub sheetCount = ActiveWorkbook.Sheets.Count If IsError(CDbl(datatoFind)) = False Then datatoFind = CDbl(datatoFind) For counter = 1 To sheetCount Sheets(counter).Activate Set cellFound = Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlValues, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) If Not cellFound Is Nothing Then If cellFound.Address <> cellToFind.Address And _ cellFound.Parent.Name <> cellToFind.Parent.Name Then notFound = False cellFound.Activate GoTo WorksEnd End If End If Next counter Next c WorksEnd: If notFound = True Then originalSheet.Activate MsgBox ("Value not found") End If End Sub 

我希望这有助于理解…

有一些问题。 第一个是你正在search所有的表单。 第一场比赛可能在包含你的比赛列的表单中!

当在表单中循环时,排除包含要find的项目列的工作表……………….还有其他问题