使用vba遍历每个excel表

时间:2016-11-25 13:50:52

标签: excel vba excel-vba

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

我正在构建一个按钮,通过每个工作表搜索Sheet10.Cells(2,4)中的值。当它发现值等于自身时,它返回Sheet10.Cells(1,1)中的值。如果找不到该值,然后将'No such player'返回到Sheet10.Cells(1,1)。 请检查代码,不确定哪个出错。它似乎永远不会遍历所有工作表。

4 个答案:

答案 0 :(得分:2)

试试这个:

'A'<=newPlate[i] && newPlate[i]<='Z')

答案 1 :(得分:1)

将你的循环嵌入

For each Sheets in ThisWorkbook
....
Next Sheets

答案 2 :(得分:0)

这将为你做到:

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

答案 3 :(得分:0)

您的代码可以重构,如下所示:

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, i.e. without exiting sub at first matching player
End Sub

请注意:

  • 您要循环浏览Worksheets集合,而不是Sheets一个

    因为Sheets收集了来自WorksheetsCharts个集合的所有元素

    后者收集Chart Objects,其中没有任何Cells()属性

  • e.Cells(2, 30) = 0将写在所有工作表中,直到第一个与匹配的播放器

    这是你真正想要的吗?