2012-12-12 90 views
1

我有一個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

+0

循環將在最後一張工作表中結束,但您沒有正確使用它們。你想在這裏做什麼?該代碼有不止一個問題.... –

+0

在最後一個工作表之後,「ForWork ws in ThisWorkbook.worksheets/Next ws」不會停止嗎? – rajah9

+0

如果您需要在最後一個工作表之前退出,那麼您可以使用'退出For' –

回答

1

根據您的問題後,結束了,你只需要檢查的工作指標,看它是否爲6,如果是的話退出了循環。見下文。關於你的評論;您需要將其更改爲打開工作簿的方法,以便在打開工作簿時僅運行一次。

在附註中,您的第一個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 
+0

感謝您的幫助....你是正確的,我需要解釋更多...我會比如在本工作簿中提示每個工作表的日期......目前,當我將其更改爲Workbook_Open時,它只會提示第一張工作表.​​..我如何獲取它以提示其他人? – TankTank

+0

@TankTank您只需將輸入框移到FOR循環內部並在Sheet.Index檢查之後。我更新了代碼以反映這一點。我認爲你的兩個FOR循環是分開的,你仍然會遇到一個問題。 – Sorceri

+0

你是對的我有問題與FOR循環被分離...感謝您的幫助。 – TankTank