我有一个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)之后结束循环。
答案 0 :(得分: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