VBA – 根据(n + 1) – (n)值添加空白行,然后删除中间值,如果小于一个值

所以我正在编写一个VBA来尝试自动化一些数据分析,这将循环通过数据,并且任何时候行中的时间差超过一秒的延迟(数据的分辨率更高),它将添加一个空行,指示一个新的数据的“testing运行”。 然后,我想要删除空行之间的任何行(调用RangeA),如果RangeA是2秒(即短testing运行是没有意义的)。

我已经设法创build了一些添加空白行的气质的代码,但是它在我的if语句中返回'types不匹配'。

之后我需要从这个数据创build一个图表,所以我不确定添加空行是否是最好的方式,否则会导致以后的问题。

编辑 – 发现有些单元格中有string,因为我之前搞错了一些macros。 所以它现在用空行来分隔数据,现在是在每个块中消除less于2秒的任何事情。

Sub dataSeperator() Dim rowStart As Long Dim rowEnd As Long Dim rowLoop As Long Dim FindColumn As Range rowStart = 3 rowEnd = Sheets("Data").UsedRange.Rows(Sheets("Data").UsedRange.Rows.Count).row With Sheets("Data") Set FindColumn = Cells.Find(What:="Time", After:=.Cells(1, 1), LookIn:=xlValues, LookAt:= _ xlWhole, MatchCase:=False) End With For rowLoop = rowEnd To rowStart Step -1 With Sheets("Data").Cells(rowLoop, FindColumn.Column) If Cells(rowLoop - 1, FindColumn.Column) - Cells(rowLoop, FindColumn.Column) < -1 Then .EntireRow.Insert End If End With Next rowLoop End Sub 

我的第一个答案仍然存在,但在我看来,如果按照以下方式工作,则可以提高代码的可读性和简单性。 你怎么看?:

 Sub Seperator2() Const TableHeaderRowNumber As Long = 1 Dim cellTableHeaderWithTime As Range Dim rngMyTable As Range Dim rngMyColumnOfTimes As Range Dim rowStart As Long Dim rowEnd As Long Dim lngCounter As Long With Sheets("Data") Set cellTableHeaderWithTime = .Cells.Find(What:="Time", After:=.Cells(TableHeaderRowNumber, 1) _ , LookIn:=xlValues _ , LookAt:=xlWhole _ , MatchCase:=False) rowStart = TableHeaderRowNumber + 2 rowEnd = .UsedRange.Rows(.UsedRange.Rows.Count).Row Set rngMyTable = .Range(.Cells(rowStart, cellTableHeaderWithTime.Column), .Cells(rowEnd, cellTableHeaderWithTime.Column)) ' Just get the column of cells you need to compare Set rngMyColumnOfTimes = Intersect(rngMyTable, cellTableHeaderWithTime.EntireColumn) For lngCounter = rngMyColumnOfTimes.Cells.Count To rowStart Step -1 'rngMyTable(lngCounter) is shorthand for rngMyTable.item(lngCounter) With rngMyTable(lngCounter) Debug.Print .Address If .Offset(-1, 0) - .Value < -1 Then .EntireRow.Insert End If End With Next lngCounter End With End Sub 

我希望这有帮助。

 Seperator() Dim rowStart As Long Dim rowEnd As Long Dim rowLoop As Long Dim FindColumn As Range rowStart = 3 With Sheets("Data") rowEnd = .UsedRange.Rows(.UsedRange.Rows.Count).row ' replaced "Cells" with ".cells" Set FindColumn = .Cells.Find(What:="Time", After:=.Cells(1, 1), LookIn:=xlValues, LookAt:= xlWhole, MatchCase:=False) End With For rowLoop = rowEnd To rowStart Step -1 With Sheets("Data").Cells(rowLoop, FindColumn.Column) ' Used .Value instead ' "Cells" refers to the active sheet! ' use Sheets("Data").Cells instead If Sheets("Data").Cells(rowLoop - 1, FindColumn.Column) - .value < -1 Then ' If Cells(rowLoop - 1, FindColumn.Column) - Cells(rowLoop, FindColumn.Column) < -1 Then .EntireRow.Insert End If End With Next rowLoop End Sub