我已经读过很多关于我遇到的相同错误的线程,其中一些线程说必须声明工作表或活动表。我试过了,但是没用。 我收到“运行时错误'91'对象变量未设置” 错误。
这是我的代码(据我所知,它写得不好,一团糟,对此深表歉意),我还要感谢代码的任何增强。
Option Explicit
Sub BBBB()
Dim wb As Workbook
Dim batStartRow As Integer
Dim batEndRow As Integer
Dim StartRangeCell As Variant
Dim StartRange As Range
Dim vVal
Dim i As Integer
Dim FirstDate As Variant
For i = 0 To Application.WorksheetFunction.Max(Range("E:E"))
Set wb = ThisWorkbook
Sheet5.Select
With Sheets("10mins")
batStartRow = .Range("E:E").Find(What:=i, after:=.Range("E1"), MatchCase:=True, LookAt:=xlWhole).Row
batEndRow = .Range("E:E").Find(What:=i, after:=.Range("E1"), searchdirection:=xlPrevious, MatchCase:=True, LookAt:=xlWhole).Row
Set StartRange = Range("E" & batStartRow & " :E" & batEndRow).Offset(0, -3)
For Each StartRangeCell In StartRange.Cells
vVal = "100"
If (WorksheetFunction.CountIf(Range("B" & batStartRow & ":B" & StartRangeCell.Row), vVal) = 1) Then
StartRangeCell.Offset(0, 17) = "y"
Set FirstDate = StartRangeCell.Offset(0, -1)
Range("S" & batStartRow) = "y"
Else
End If
Next
End With
Next
End Sub
数据:
Time AA BB CC
1/27/2018 12:38 0 7
1/27/2018 12:48 24 7
1/27/2018 12:58 62 8 y
1/27/2018 13:08 100 8 y
1/27/2018 13:18 100 8
1/27/2018 13:28 100 8
1/27/2018 13:38 100 8
1/27/2018 13:48 100 8
1/27/2018 13:58 100 8
1/27/2018 14:08 11 8
1/27/2018 14:18 3 8
1/27/2018 14:28 1 8
1/27/2018 14:38 0 8
1/27/2018 14:48 0 8
1/27/2018 14:58 0 8
1/27/2018 15:08 0 8
1/27/2018 15:18 0 8
1/27/2018 15:28 0 8
1/27/2018 15:38 0 8
1/27/2018 15:48 0 8
1/27/2018 15:58 0 8
1/27/2018 16:08 0 8
1/27/2018 16:18 0 8
1/27/2018 16:28 0 8
1/27/2018 16:38 0 8
1/27/2018 16:48 0 8
1/27/2018 16:58 0 8
1/27/2018 17:08 0 8
1/27/2018 17:18 0 8
1/27/2018 17:28 0 8
1/27/2018 17:38 0 8
1/27/2018 17:48 25 8
1/27/2018 17:58 52 9 y
1/27/2018 18:08 100 9 y
1/27/2018 18:18 100 9
1/27/2018 18:28 100 9
代码目标:
对于“ BB”列中的每个集合,我希望在“ CC”列中有一个“ y”,对应于数字“ 100”首次出现在“ AA”列中。
下一步是计算达到“ 100”所需的时间。
感谢您的帮助。再次谢谢你!
答案 0 :(得分:3)
您需要测试一下使用Range后是否发现了任何东西。例如
首先将Range.Find的结果存储在变量中,然后测试在Find操作期间是否将它们设置为Nothing以外的其他值。
此外,将Integers
更改为Long
,以避免潜在的溢出。
例如
Dim batStart As Range, batEnd As Range
Set batStart = .Range("E:E").Find(What:=i, after:=.Range("E1"), MatchCase:=True, LookAt:=xlWhole)
Set badEnd = .Range("E:E").Find(What:=i, after:=.Range("E1"), searchdirection:=xlPrevious, MatchCase:=True, LookAt:=xlWhole)
If Not batStart Is Nothing Then
batStartRow = batStart.Row
'Other code.....
End If
与batEnd
相同。
将其余要做的事情放在该If语句中。
这是仅在两个范围都设置好的情况下才使用代码的方式:
With Worksheets("10mins")
Set batStart = .Range("E:E").Find(What:=i, after:=.Range("E1"), MatchCase:=True, LookAt:=xlWhole)
Set badEnd = .Range("E:E").Find(What:=i, after:=.Range("E1"), searchdirection:=xlPrevious, MatchCase:=True, LookAt:=xlWhole)
If batStart Is Nothing Or batEnd Is Nothing Then Exit Sub
batStartRow = batStart.Row
batEndRow = batEnd.Row
Set startRange = Range("E" & batStartRow & " :E" & batEndRow).Offset(0, -3)
For Each startRangeCell In startRange.Cells
'your code continue....