Excel VBA中的结束循环

我有一个Excel VBA的工作簿。 如何在工作表上结束循环? 我不确定如何做到这一点。 这是代码。

Private Sub Workbook_SheetActivate(ByVal Sh As Object) Dim dtDate As Date Dim intHours As Long Dim ws As Worksheet intHours = 11 dtDate = InputBox("Date", , Date) For Each ws In ThisWorkbook.Worksheets Set SelRange = Range("A6:A366") Next ws(**This where I need the loop to stop after the last worksheet**) For Each b In SelRange.Rows b.Value = dtDate + TimeSerial(intHours, 0, 0) b.Value = dtDate + TimeSerial(intHours, intMinutes, 0) intHours = intHours intMinutes = intMinutes + 1 If intHours > 24 Then intHours = intHours - 24 End If Next End Sub 

我需要循环在工作表6的最后一个工作表之后结束。

根据你的问题,你只需要检查工作表索引,看看它是否是6,如果是的话,退出for循环。 见下文。 关于你的意见; 您需要将其更改为打开工作簿打开方法,以便在打开工作簿时仅运行一次。

在附注中,你的第一个FOR循环超出了第二个FOR循环的范围,所以你只需重复设置范围,直到第一个FOR循环结束。 解释一下你想要完成的事情可能会更好,这样你可以得到更好的回应。

 Private Sub Workbook_Open() Dim dtDate As Date Dim intHours As Long Dim ws As Worksheet intHours = 11 For Each ws In ThisWorkbook.Worksheets 'check the index of the worksheet and exit if it is 6 If ws.Index = 6 Then Exit For End If 'get the date per sheet dtDate = InputBox("Date", , Date) Set SelRange = Range("A6:A366") Next ws '(**This where I need the loop to stop after the last worksheet**) For Each b In SelRange.Rows b.Value = dtDate + TimeSerial(intHours, 0, 0) b.Value = dtDate + TimeSerial(intHours, intMinutes, 0) intHours = intHours intMinutes = intMinutes + 1 If intHours > 24 Then intHours = intHours - 24 End If Next End Sub 

这是我认为你正在寻求完成。

 Private Sub Workbook_Open() Dim dtDate As Date Dim intHours As Long Dim ws As Worksheet intHours = 11 For Each ws In ThisWorkbook.Worksheets dtDate = InputBox("Date", , Date) 'check the index of the worksheet and exit if it is 6 If ws.Index = 6 Then Exit For End If Set SelRange = ws.Range("A6:A366") For Each b In SelRange.Rows b.Value = dtDate + TimeSerial(intHours, 0, 0) b.Value = dtDate + TimeSerial(intHours, intMinutes, 0) intHours = intHours intMinutes = intMinutes + 1 If intHours > 24 Then intHours = intHours - 24 End If Next Next ws '(**This where I need the loop to stop after the last worksheet**) End Sub