我目前正在编写一个简单的宏来确定在哪个时段安排了谁,并将该时段记录在另一个工作表上。一切正常,直到将最后一个时段的人的名字与最后一个时段进行比较。此时for循环" j"转到-1并导致宏错误输出。
我在下面包含了我的整个代码,但这是调试器指向的行 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
感谢任何人提供的任何帮助。这让我疯了,我现在已经数不清楚了几个小时。
答案 0 :(得分:1)
正如道格所指出的那样,问题就在于行
j = 17 Or j = 18
由于没有If
,VBA会尝试将其评估为j
的分配
j = (17 Or j = 18)
现在什么是17 Or j = 18
?右侧j = 18
为True
,因为此时j
为18。所以我们有
j = (17 Or True)
现在我们可以说anything Or True
总是正确但我们可以更深入一点。你如何使用Or
数字?您可以使用二进制数的按位比较,例如
00001011
Or 00010010
-----------
= 00011011
我们在处理数字和布尔值时也这样做。 False
存储为全0,True
存储为全1,这会产生Not
,And
,Or
,{{1}所需的确切行为}}。例如。 XOr
成为:
anything Or True
当然,仅使用1位也会显示相同的行为,但我们没有1位数据类型。因此 xxxxxxxx
Or 11111111
-----------
= 11111111
为17 Or j = 18
,其存储为True
,当作为整数读取时为11...11
。
请注意,我忽略了数据类型的不同字节大小。
VBA为你做了很多隐式转换,这可能很好,特别是对于数字&lt; - &gt;字符串,但它可以导致问题,只有在代码后面才会出现。 例如,意外地将数字存储为字符串然后将其添加到实际数字将起作用(字符串将被转换)。但是,添加两个数字字符串会将它们连接起来。