如何搜索范围以查看范围是否缺少一行
问题描述:
我有一组数据包含一个月内每小时的统计数据。如何搜索范围以查看范围是否缺少一行
有时,数据缺少一行(例如,当数据库因维护而关闭时,所以我们无法收集统计数据)。我需要做的是确定每个24小时内每小时的列是否增加1。如果在小时列的值由2增大,我需要添加一个空白行,并填充每个单元具有0
这就是我试图做:
Sub btnAddZero()
Dim srcRange As Range
Dim intOffset As Integer
'select the starting row for counting the hours
Set srcRange = Sheets("Raw Data").Range("A4")
'Set the beginning offset to 4 to account for empty 4 rows
intOffset = 4
'number of days in the month
For j = 0 To 30
'number of hours in a day
' rows
Dim i As Integer
For i = 0 To 23
'if the first cell is not 1 more than the cell below it
If srcRange.Cells(intOffset, 4) <> srcRange.Cells(intOffset + i, 4) Then
'shift everything below this line down
srcRange.Rows(intOffset + i).Insert shift:=xlShiftDown
'set everything in this row to be 0
srcRange.Cells(intOffset + i, 1).Value = 0
srcRange.Cells(intOffset + i, 2).Value = 0
'set the value to be the same value as the cell above
srcRange.Cells(intOffset + i, 3).Value = srcRange.Cells(Row - 1, 3).Value
srcRange.Cells(intOffset + i, 4).Value = 0
srcRange.Cells(intOffset + i, 5).Value = 0
End If
Next i
intOffset = intOffset + i
'off set the range for next 24 hours
Set srcRange = srcRange.offset(intOffset)
Next j
End Sub
不幸...这将行的巨大范围设置为0(我相信它插入〜22到28行0)。第一次通过外部for循环,在内部for循环的第4次迭代之后,这是0的行开始的地方。
我相信我的第一个也是最大的问题是,我的检查是否有缺失的时间是不正常工作。
任何帮助将不胜感激!
以下是我正在使用的少量数据,您可以看到第4列中缺少值15。我想,它包含14
9292 12377 2017年1月30日12 2471
11195 15028 2017年1月30日13 1392
5393 6335行后添加一行0的2017- 01-30 14 374
1911年1959年2017年1月30日16 8
11995 13181 2017年1月30日17 181
答
我想你是如何检测的缺失小时的逻辑并插入行是不正确的。看问题有点不同,我想出下面的逻辑作为例子。希望这可以让你更接近解决方案。
Option Explicit
Sub MissingHourCheck()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("Raw Data")
Dim timeSlot As Range
Dim nextTimeSlot As Range
Set timeSlot = ws.Range("D5")
Set nextTimeSlot = timeSlot.Offset(1, 0)
Dim expectedHour As Long
expectedHour = 0
Do While Not IsEmpty(nextTimeSlot.Value)
If expectedHour <> timeSlot.Value Then
'--- oops, we're missing at least one hour.
' how many hours (rows) do we need to insert?
Dim missingHours As Long
If timeSlot.Value > expectedHour Then
'--- it's the middle of the day, our math is easy
missingHours = timeSlot.Value - expectedHour
Else
missingHours = 23 - expectedHour + 1
End If
timeSlot.Resize(missingHours).EntireRow.Insert Shift:=xlShiftDown
expectedHour = expectedHour + missingHours
Else
Set timeSlot = timeSlot.Offset(1, 0)
Set nextTimeSlot = timeSlot.Offset(1, 0)
expectedHour = expectedHour + 1
End If
If expectedHour >= 24 Then
expectedHour = 0
End If
Loop
End Sub
+0
这非常接近我所需要的!再次感谢你的帮助! – Sarah
第4列中的什么类型的值(可能是时间戳)?这是一个日期还是时间?它会永远在一个小时吗? – PeterT
这是一个整数,从0-23这取决于一天中的小时 – Sarah