2016-11-25 57 views
0
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)通过每个sheet.When它发现等于它本身的价值将其返回在该值Sheet10.Cells(1,1)。如果没有找到该值,则将'No such player'返回到Sheet10.Cells(1,1)。 请检查代码,不知道哪里出错。它似乎永远不会遍历所有表。循环每一个擅长使用VBA

回答

2

试试这个:

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 
+0

不工作..... – honesty1997

+0

显示一些错误或仍然不停止在你想要的工作表上? – Limak

+0

哦!它的工作原理!谢谢! 我刚刚重新打开文件几次。 – honesty1997

1

巢你的循环到

For each Sheets in ThisWorkbook 
.... 
Next Sheets 
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 
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将被写入所有工作表,直到第一个与之相配的球员

    这是你真正想要的是什么?