1

我有一个用于工作簿的 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 之后结束循环。

4

1 回答 1

1

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

附带说明一下,您的第一个 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
于 2012-12-12T17:36:50.093 回答