2016-11-25 69 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將被寫入所有工作表,直到第一個與之相配的球員

    這是你真正想要的是什麼?