Excel VBA – 通过电子表格循环并预制另一个循环

我可能只是做错了什么。

我试图通过每个工作表循环在工作簿中,并在每个工作表上,我希望它preform另一个循环。 问题是我没有移动到下一个工作表,只能在活动工作表上工作。 任何帮助,将不胜感激。

Sub Hours() Dim ws As Worksheet Dim I As Integer For Each ws In ActiveWorkbook.Worksheets For I = 6 To 21 k = I + 1 If Cells(k, 7).Value = "" Then ElseIf Cells(I, 8).Value <> Cells(k, 7) Then Cells(I, 8).Font.Color = vbRed Cells(k, 7).Font.Color = vbRed End If Next I Next ws End Sub 

尝试下面的代码,使用With ws语句获取所有对象,例如使用当前Worksheet进行循环的Cells格。

 Sub Hours() Dim ws As Worksheet Dim i As Long, k As Long For Each ws In ActiveWorkbook.Worksheets With ws For i = 6 To 21 'k = i + 1 ' not needed, just change k to i + 1 ' merge 2 Ifs to one using an And If .Cells(i + 1, 7).Value <> "" And .Cells(i, 8).Value <> .Cells(i + 1, 7) Then .Cells(i, 8).Font.Color = vbRed .Cells(i + 1, 7).Font.Color = vbRed End If Next i End With Next ws End Sub 

我用它来循环我的工作表:

  For i = 1 To ActiveWorkbook.Worksheets.Count ActiveWorkbook.Worksheets(i) 'adapt your code into that Next i 

这可能对你更好

你必须告诉vbaselect下一个工作表。 现在,它正在循环使用工作表的数量,但是由于代码中没有任何内容激活下一个工作表,它只是在第一个工作表上循环。 尝试这个:

 Sub Hours() Dim ws As Worksheet Dim I As Integer For Each ws In ActiveWorkbook.Worksheets ws.Activate For I = 6 To 21 k = I + 1 If Cells(k, 7).Value = "" Then ElseIf Cells(I, 8).Value <> Cells(k, 7) Then Cells(I, 8).Font.Color = vbRed Cells(k, 7).Font.Color = vbRed End If Next I Next ws End Sub 

只是为了给你一些额外的信息,我通常使用这个代码来处理通过工作表循环:

 sub example() ws = ThisWorkbook.Worksheets.Count for i = 1 to ws 'other code next i end sub 

我喜欢这样做的方式是我有更多的灵活性,不一定循环所有的工作表。 我经常不想在第一个或最后一个工作表上执行一个过程。 为了做到这一点,我可以像这样调整for语句:

 'to not loop through the last worksheet for i = 1 to ws - 1 'to not loop through the first worksheet for i = 2 to ws 

我喜欢这种方式更灵活。 当然,如果你想循环使用每个工作表for each ws方法更简单,因为你不必定义一个variables。 我只是想扩大这个主题。

考虑一下。

 Sub Test1() 'UpdatebyExtendoffice20161222 Dim x As Integer Dim ws As Worksheet ' Begin looping through the sheets For Each ws In ActiveWorkbook.Worksheets ws.Select ' Begin looping through the cells ' Set numrows = number of rows of data. NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count ' Select cell a1. Range("A1").Select ' Establish "For" loop to loop "numrows" number of times. For x = 1 To NumRows ' Insert your code here. ' Selects cell down 1 row from active cell. ActiveCell.Offset(1, 0).Select ' After a blank cells is found, move to the next sheet Next Next ws End Sub