我目前正在写一个简单的宏来确定谁在哪个时间段安排,并在另一个工作表上记录该时间段。一切正常,直到最后一个时间段的人员的姓名与最后一个时间段相比较为止。此时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)。 –