[英]Loop through each excel sheet using 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)中的值。找不到,然后將“否此類播放器”返回到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
將循環嵌套
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, i.e. without exiting sub at first matching player
End Sub
請注意:
您要遍歷Worksheets
集合而不是工作Sheets
一個
因為工作Sheets
收集Worksheets
和Charts
集合中的所有元素
后者收集沒有任何Cells()
屬性的Chart Object
s
e.Cells(2, 30) = 0
將被寫入所有工作表,直到第一個具有匹配播放器的工作表
這是您真正想要的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.