【发布时间】:2014-11-06 03:00:37
【问题描述】:
我有价格数据,每天记录多个但数量不定的价格。在另一张纸上,我有一个所有单独日期的列向量。在每一天旁边,我需要一个包含当天所有价格的行向量。
我认为最好的方法是每天复制价格并将它们放入一个数组中,我可以将其粘贴并转置到另一张表中。为此,我创建了两个循环,但我不知道如何存储每一天的价格并在我通过循环时为每一天填充这个动态大小的数组。我想我必须在每个循环中重新调整数组,但是当我通过循环时如何填充数组的每个元素?
这是我所在位置的副本。
Sub GroupDayData()
Dim RowCount As Integer
Dim RowCount2 As Integer
Dim r As Integer
Dim j As Integer
Dim Day As Date
Dim No1 As Worksheet
Dim No2 As Worksheet
Dim TradePrice() As Double
No1 = Worksheets("Sheet1")
No2 = Worksheets("Sheet4")
RowCount = Application.CountA(No1.Range("A:A"))
RowCount2 = Application.CountA(No2.Range("A:A"))
Application.ScreenUpdating = False
'First I want to set the particular day I am looking at
For r = 1 To RowCount2 + 1
Day = Range("A" & r)
'I then want to look at all values on that day
For j = 1 To RowCount + 1
If No1.Range("A" & j) = Day Then
'This is where I am stuck. I want the code to populate an array as it runs through
'this second loop, which I will paste and transpose in Sheet4, and then do the whole
'thing again for the next day, therefore the size of the array is not constant.
Application.ScreenUpdating = True
End Sub
在 cmets 之后,我已经编辑了代码,但是我仍然没有得到任何输出出现在 Sheet 2 (No2) 中。问题似乎是有效地填充数组,并将其粘贴到选定的范围内。
Sub DayData()
Dim RowCount As Integer
Dim ClmnCount As Integer
Dim r As Integer
Dim j As Integer
Dim No1 As Worksheet
Dim No2 As Worksheet
Dim Day As Date
Dim Price() As Variant
'Does this need to be declared as Double?
Dim e As Integer
Set No1 = Worksheets("Sheet1")
Set No2 = Worksheets("Sheet2")
RowCount = No1.Application.CountA(No1.Range("A:A")) + 1
ClmnCount = No2.Cells(1, Columns.Count).End(xlToLeft).Column
Application.ScreenUpdating = False
For r = 1 To ClmnCount
Day = No2.Cells(1, r)
For j = 1 To RowCount
If No1.Range("A" & j).Offset(1, 0) = Day Then
'This loop will look through all date values and count the number that are the same
e = e + 1
'First I need to count how many elements are in the particular array
ReDim Preserve Price(e)
'Redim the array with its size
'Is there a more efficient way rather than using redim each loop
Price(e) = Range("B" & j).Offset(1, 0).Value
'I think the problem is here
End If
Next j
No2.Range(Cells(2, r), Cells(e + 1, r)) = Price
Erase TradePrice
Next r
Application.ScreenUpdating = False
End Sub
【问题讨论】:
-
只需使用
Variant Variable即可一次性获取所有范围值。要获取范围,请使用 范围过滤方法。