使用vba循环访问每个Excel表

Sub CommandButton1_Click() c = 0 For Each e In Sheets e.Cells(2, 30) = 0 If e.Cells(2, 15) = Sheet10.Cells(2, 4) Then Sheet10.Cells(1, 1) = e.Cells(2, 15) c = 1 Exit For End If Next e If c = 0 Then Sheet10.Cells(1, 1) = "No such player" End If End Sub 

我目前正在build立一个button,通过每张工作表searchSheet10.Cells(2,4)中的值。当它find等于它自己的值时,返回Sheet10.Cells(1,1)中的值。如果值找不到,然后将“No such player”返回到Sheet10.Cells(1,1)。 请检查代码,不知道哪里出错。它似乎从来没有遍历所有表。

试试这个:

 Sub CommandButton1_Click() Dim e As Worksheet c = 0 For Each e In ActiveWorkbook.Worksheets e.Cells(2, 30) = 0 If e.Cells(2, 15) = Sheet10.Cells(2, 4) Then Sheet10.Cells(1, 1) = e.Cells(2, 15) c = 1 Exit For End If Next If c = 0 Then Sheet10.Cells(1, 1) = "No such player" End If End Sub 

把你的循环embedded

 For each Sheets in ThisWorkbook .... Next Sheets 

这将为你做到这一点:

 Sub CommandButton1_Click() Dim sh As Worksheet, sPlayer As String, rng As Range sPlayer = Sheets("Sheet10").Cells(2, 4).Value 'Turns the player into a string For Each sh In ActiveWorkbook.Sheets Set rng = Nothing 'resets the range Set rng = sh.Cells.Find(What:=sPlayer, After:=ActiveCell, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True, SearchFormat:=False) ' This check is to see if the "find" found the player in the sheet (looking for exact matches and only value - not formulas) If Not rng Is Nothing And sh.Name <> "Sheet10" Then 'If it did find the player (and it's not on "Sheet10", where the input value is Sheets("Sheet10").Cells(1, 1).Value = sPlayer ' puts in the player in A1 Exit Sub ' Exits sub (as it's found what it's looking for ElseIf sh.Index = ActiveWorkbook.Sheets.Count Then Sheets("Sheet10").Cells(1, 1).Value = "No such player" ' End of loop and workbook says it can't find them End If Next End Sub 

你的代码可以重构如下:

 Sub CommandButton1_Click() For Each e In Worksheets '<--| loop through 'Worksheets' only e.Cells(2, 30) = 0 '<--? If e.Cells(2, 15) = Sheet10.Cells(2, 4) Then Sheet10.Cells(1, 1) = e.Cells(2, 15) Exit Sub End If Next e Sheet10.Cells(1, 1) = "No such player" '<--| this line would only be reached if 'For Each loop' has been completed, ie without exiting sub at first matching player End Sub 

请注意:

  • 你想循环通过Worksheets集合,而不是Sheets之一

    因为SheetsWorksheetsCharts集合中收集所有元素

    后者收集Chart Object ,没有任何Cells()属性

  • e.Cells(2, 30) = 0将被写入所有的工作表,直到第一个匹配的玩家

    这是你真正想要的吗?