简体   繁体   中英

How to insert array formula into Excel via VBA?

Previously I have an Excel VBA code that performs index & match formula from 1 sheet to another for an entire column in a table. Code example as below:

With Me.Range("table1[Description]")
    .Formula = "=IFerror(INDEX(table2,MATCH(B4,table2[Asset No],0),2),"""")"
    .Value = .Value
 End With

Now I would like to add an array function into the sheet so I copied the formula and replace the old formula with array along with other modifications.

Sub refresh()

With Me.Range("table1[Last Service Date]")
    .FormulaArray = "=LARGE(IF(table2[[#All],[Asset No]]=[@[Asset No]],table2[[#All],[Entry Date]]),2)"
    .Value = .Value
End With

End Sub

But when I try to test the code, I keep getting the error message 400. Anything I need to change in my code for array formulas?

What's the point of using Me in the code? Have you placed that code in the Sheet Module? I would suggest you to move this code on to the Standard Module like Module1 and replace the Me keyword with the proper sheet reference. Otherwise I hope you have a good reason to place that code into the sheet module.

Also you should place the Array Formula in the first cell of the table in the desired column and since the data is formatted as an Excel Table, the whole column will be filled with the formula automatically. If not, you can then use AutoFill property to fill down the formula down the rows.

Give this a try to see if that resolves your issue. The answer assumes that the formula you are trying to place through VBA works well when you put it manually on the Sheet.

With Me.Range("table1[Last Service Date]").Cells(1)
    .FormulaArray = "=LARGE(IF(table2[[#All],[Asset No]]=[@[Asset No]],table2[[#All],[Entry Date]]),2)"
    .Value = .Value
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM