我目前正在寫一個簡單的宏來確定誰在哪個時間段安排,並在另一個工作表上記錄該時間段。一切正常,直到最後一個時間段的人員的姓名與最後一個時間段相比較爲止。此時for循環「j」變爲-1並導致宏出錯。簡單的嵌套for循環出錯1004錯誤
我已經包括了我的全部代碼如下但這
Dim mySheet As Worksheet, masterSheet As Worksheet, myBook As Workbook 'Define your workbooks and worksheets as variables
Option Compare Text 'Makes string comparisons case IN-sensitive
Sub Watch_Bill()
Set myBook = Excel.ActiveWorkbook
Set masterSheet = Sheets("Musters")
MsgBox masterSheet.Name
Dim memberName, memberFirstWatch, memberSecondWatch As String
Dim lastRow As Integer
Dim watchStation, watch As String
lastRow = masterSheet.Range("A1").CurrentRegion.Rows.Count
'lastColumn = ActiveSheet.Range("A1").CurrentRegion.Columns.Count
'Cycle through each member of the duty section
For i = 2 To lastRow
memberName = masterSheet.Cells(i, 2).Value
'Cycle through watch bill to find member's watches
For j = 9 To 18 'Row 9 starts the section of the watchbill that contains watches
'MsgBox j
For k = 2 To 9 'Column 2 through 9 contain watches
watchStation = ActiveSheet.Cells(j, k).Value
'MsgBox watchStation
If InStr(watchStation, memberName) <> 0 Then
'Determine what watch station member is on
If j = 9 Or j = 10 Then
watch = "0700-1200"
ElseIf j = 11 Or j = 12 Then
watch = "1200-1700"
ElseIf j = 13 Or j = 14 Then
watch = "1700-2200"
ElseIf j = 15 Or j = 16 Then
watch = "2200-0200"
Else: j = 17 Or j = 18
watch = "0200-0700"
End If
'MsgBox "Found member"
'Check if member already had watch
If memberFirstWatch = "" Then
'MsgBox "member's first watch"
memberFirstWatch = watch
Else
'MsgBox "member's second watch"
memberSecondWatch = watch
End If
'Fill in member's watch times on muster sheet
masterSheet.Cells(i, 11).Value = memberFirstWatch
masterSheet.Cells(i, 12).Value = memberSecondWatch
End If
Next k
Next j
memberFirstWatch = ""
memberSecondWatch = ""
Next i
End Sub
感謝所有幫助任何人都可以提供在線調試器指向是 watchStation = ActiveSheet.Cells(J,K).value的
。這讓我感到非常緊張,而且現在我還沒有弄明白這個問題。
我想你需要將Else的末尾改成另一個ElseIf。因爲它現在是你設置j爲真(17或j = 18)。 –