简单的嵌套for循环出错1004错误

我目前正在编写一个简单的macros,以确定在哪个时间段内安排谁,并在另一个工作表上logging该时间段。 一切正常,直到最后一个时间段的人员的姓名与上一个时间段相比较为止。 此时for循环“j”变为-1并导致macros出错。

我在下面包括了我的整个代码,但这是debugging器指向的行是watchStation = ActiveSheet.Cells(j,k).Value

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 

感谢任何人都可以提供的帮助。 这使我疯狂,而且我现在还没有弄明白。

道格是对的。 我会试着解释发生了什么。 任何人都可以随时纠正我。

正如Doug指出的那样,问题在于线条

 j = 17 Or j = 18 

由于没有If ,VBA试图评估它作为一个j的任务

 j = (17 Or j = 18) 

现在是17 Or j = 18 ? 因为当时j是18,所以右边j = 18True 。 所以我们有

 j = (17 Or True) 

现在我们可以说,“ anything Or True总是如此,但我们可以深入一点。 你如何使用数字Or数字? 您使用二进制数的按位比较,例如

  00001011 Or 00010010 ----------- = 00011011 

在处理数字和布尔值时,我们也是这样做的。 False被存储为全0, True被存储为全1,这就产生了我们想要的, NotAndOr XOr的确切行为。 例如, anything Or True变成

  xxxxxxxx Or 11111111 ----------- = 11111111 

当然,只使用1位也会显示相同的行为,但我们没有1位数据types。 所以17 Or j = 18True ,它被存储为11...11 ,当作为一个整数读取时是-1

请注意,我忽略了不同的数据types的字节大小。

VBA为你做了很多隐式转换,这对你来说可能是很好的,特别是对于数字string,但是它可能会导致问题在代码中稍后出现。 例如不小心将一个数字存储为一个string,然后将其添加到实际的数字将工作(该string将被转换)。 但是添加两个数字string会连接它们。