基于另一个数组select一个数组中的值

我之前在VBA中做过一些比较简单的事情,但是我认为对于这个项目,我需要进入使用variables和可能的数组,而这些variables现在看起来已经超出了我的范围。

我有4列数据:col。 A是开始时间,col。 B是相应的结束时间(每个将会有大约30个),col。 C是数据点的时间戳(在列A和B中指定的时间段期间和之间收集;这些列中有40,000多行数据)和列。 D是在列中引用的每个时间点观察到的数据。 C.每个文件将有不同的开始/结束时间,所以我想要一个macros,可以从单元格中读取它们。

我需要将时间戳记和数据点从A列和B列中指定的每个时间段分成不同的列(例如,时间段1的数据将在列F和G中,时间段2的数据将在H和I等)。 所以,我想写一个macros,将本质上search列。 C代表第一时间段的开始时间和结束时间之间的值,并将相关数据复制/粘贴到适当的新列中。

我一直在疯狂地Googlesearch,但是我很难将各种代码段放在一起,以解决不同的步骤。 这是我到目前为止(以及一些说明我认为事情应该做的事情):

Sub CopyRows2() Dim endTime As Range, startTime As Range Dim copyRange As Range, lastRow As Range, timePoint As Range Dim i As Long, k As Long Set startTime = ActiveSheet.Cells(i, 2).Value lastRow = ActiveSheet.Range("B" & ActiveSheet.Rows.Count).End(xlUp).Row 'find the last row of the time periods Set timePoint = ActiveSheet.Cells(2, 3) 'start looking for times in cell C2 Do Until lastRow = "" For i = 2 To lastRow Set endTime = startTime.Offset(0, 1) 'identify the end of the time period If timePoint.Value >= startTime.Value Then 'find the row with the first data point in the time period If copyRange Is Nothing Then 'this "copyRange" stuff is based on: http://stackoverflow.com/questions/9790924/excel-vba-how-to-select-rows-based-on-data-in-a-column Set copyRange = ActiveSheet.Rows(i) Else Set copyRange = Union(copyRange, ActiveSheet.Rows(1)) End If End If Next i If Not copyRange Is Nothing Then ActiveSheet.copyRange.Copy ActiveSheet.Cells(2, k) 'k is meant to be the column number, which will keep incrementing by 2 but I don't know how to tell it to do that End If Loop End Sub 

现在它给了我一个错误:

“应用程序定义或对象定义的错误”

在这一行上:

 Set startTime = ActiveSheet.Cells(i, 1).Value 

我不明白为什么。 但是,我敢肯定,它有更大的问题,它可能不会真的做我想要做的事情,即使我修复了导致错误的问题。

目前,我希望有人能够帮助的具体事情是:

  1. 什么是导致错误?

  2. 我如何定义k使它增加2(参见上面代码中的注释)

但是,我知道可能有更好的方法来做到这一点 – 如果是的话,其他的build议将不胜感激!

假设数据从第2行开始。确保范围D1不为空。

 Sub CopyRows2() Dim lastRow As Long Dim lastCol As Long Dim ws As Worksheet 'clear enough columns for ~30 data sets Columns("E:CA").ClearContents Set ws = Worksheets("Sheet2") lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row x = 2 With ws 'fill columns A+B to correspond with C Do Until Cells(lastRow, 1) <> "" If .Cells(x, 2) <> .Cells(x, 3) Then .Range("A" & x + 1 & ":B" & x + 1).Insert Shift:=xlDown .Cells(x + 1, 1) = .Cells(x, 1) .Cells(x + 1, 2) = .Cells(x, 2) End If x = x + 1 Loop 'move blocks i = 2 c = 1 Do Until i > lastRow 'change in column A If .Cells(i + 1, 1) <> .Cells(i, 1) Then .Range("c" & i - c + 1 & ":D" & i).Copy lastCol = .Cells(1, Columns.Count).End(xlToLeft).Column .Cells(1, lastCol + 1).PasteSpecial c = 0 End If i = i + 1 c = c + 1 Loop End With End Sub