如何使用evaluate方法将值填充到VBA数组中,并将它们返回给Excel工作表?

我正在尝试使用VBA EVALUATE方法中的值填充数组。 一旦数组被填充后,我想用数组中的值填充Excel工作表中的单元格范围。

我写了一个SUB做我想做的,但是当我运行这个函数,我得到以下错误:

运行时错误9:下标超出范围

所以我的问题是:如何纠正我的脚本,以使max_min_date2正确运行? 我的数据截图是在这里上传

 Sub max_min_date2(): 'Define an array Dim values As Variant 'Define the size of the array values = Range("L2:L1000").Value 'Set up for loop' For i = 2 To 1000 'Populate values in the array. values(i - 1) = Evaluate("=MAX(IF(A:A=" & Cells(i, 11).Address & ",B:B))") Next i 'Populate Excel sheet with values in the array. Range("L2:L1000").Value = values End Sub 

 Sub max_min_date2() 'Define an array Dim values As Variant Dim LastRow As Long Dim LastRow2 As Long 'set the worksheet With Worksheets("Sheet1") 'Change to your sheet 'get last row to avoid unnecessary loops LastRow = .Cells(.Rows.Count, 11).End(xlUp).Row 'get last row of ref data to avoid unnecessary calculations LastRow2 = .Cells(.Rows.Count, 1).End(xlUp).Row 'Define the size of the array make it a two dimensional for ease of assigning back to array. ReDim values(1 To LastRow - 1, 1 To 1) As Variant 'Set up for loop' For i = 2 To LastRow 'Populate values in the array. values(i - 1, 1) = .Evaluate("=MAX(IF(A2:A" & LastRow2 & "=" & .Cells(i, 11).Address & ",B2:B" & LastRow2 & "))") Next i 'Populate Excel sheet with values in the array. .Range("L2").Resize(LastRow - 1).Value = values End With End Sub 

这是我的理解,你想显示每个股票的最大和最小date。 我不相信你一直在努力的公式会按预期工作。 这是一个替代路线,通过枢轴表; 你会很快得到你的结果。

将此代码粘贴到代码模块中:

 Option Explicit Public Sub CreateMaxDateByTickerPivotTable(ByVal prngTopLeftDataCell As Excel.Range, ByVal prngPivotTableTopLeft As Excel.Range, ByVal psPivotTableName As String) Dim pt As Excel.PivotTable Set pt = Nothing On Error Resume Next Set pt = prngPivotTableTopLeft.Worksheet.PivotTables(psPivotTableName) On Error GoTo 0 If Not pt Is Nothing Then pt.TableRange2.Clear End If With ThisWorkbook.PivotCaches.Create(xlDatabase, prngTopLeftDataCell.CurrentRegion) With .CreatePivotTable(prngPivotTableTopLeft, psPivotTableName) .ShowValuesRow = False .CompactLayoutRowHeader = "Ticker" .ColumnGrand = False .RowGrand = False With .PivotFields("<ticker>") .Orientation = xlRowField .Position = 1 End With .AddDataField .PivotFields("<date>"), "Max Date", xlMax .AddDataField .PivotFields("<date>"), "Min Date", xlMin End With End With Set pt = Nothing End Sub 

然后你可以用几个参数调用上面的子代码:

 CreateMaxDateByTickerPivotTable Sheet1.Range("A1"), Sheet1.Range("K1"), "MaxDateByTicker" 

子只是build立一个数据透视表(如果它已经存在,就删除它),列出代号,并找出数据集中每个代码的最大和最小date。