Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Evaluate function and array formula returning range of values

Tags:

excel

vba

Suppose I want to use Evaluate function to evaluate an array formula which returns a range of values. For example I try to get index (using Excel function MATCH) in an ordered list in Sheet2!A:A for each values in Sheet1!A:A. And I want to put the indices in column B.

Dim sh as Worksheet
Set sh = Sheets("Sheet1")
sh.Range("B1:B10").Value = sh.Evaluate("=MATCH(A1:A10,Sheet2!A:A)")

Whan I run the code, I get a column of repeated values - the values are equal to the index of the first element. This is not correct.

When I try the same by putting array formula in the worksheet {=MATCH(A1:A10,Sheet2!A:A)}, it works without problems and returns the correct index for every element.

So my question: how to use Evaluate function returning a whole range of values?

like image 841
V.K. Avatar asked Dec 27 '14 17:12

V.K.


2 Answers

Interesting issue. I was not able to get the MATCH function to return an array using VBA Evaluate. However, the following modification seems to work, using the zero (0) for the row argument in the index function returns all of the rows. Note also that I added the match_type argument to the Match function.

sh.Range("B1:B10").Value = sh.Evaluate("=INDEX(MATCH(A1:A10,Sheet2!A:A,0),0,1)")
like image 111
Ron Rosenfeld Avatar answered Nov 19 '22 13:11

Ron Rosenfeld


If Evaluate() does not make you happy, then:

Sub marine()
    Dim sh As Worksheet, r As Range
    Set sh = Sheets("Sheet1")
    Set r = sh.Range("B1:B10")
    r.FormulaArray = "=MATCH(A$1:A$10,Sheet2!A:A,0)"
    r.Copy
    r.PasteSpecial xlPasteValues
End Sub
like image 38
Gary's Student Avatar answered Nov 19 '22 14:11

Gary's Student