我有一组数据,其中包含一个月内每小时的统计信息。
有时,数据缺少一行(例如,当数据库因维护而关闭时,我们无法收集统计信息)。我需要做的是确定每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的行之后添加一行0。
9292 12377 2017-01-30 12 2471
11195 15028 2017-01-30 13 1392
5393 6335 2017-01-30 14 374
1911 1959 2017-01-30 16 8
11995 13181 2017-01-30 17 181
答案 0 :(得分:1)
我认为你如何检测缺失时间和插入行的逻辑并不是很正确。看一下这个问题有点不同,我想出了下面的逻辑作为例子。希望它可以帮助您更接近解决方案。
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