简体   繁体   中英

Referencing a string inside a Formula Array in Excel VBA

Need some help referencing a string in an Index formula array

My code below:

Sub Loop_Test2()

Dim i As Long
Dim j As Long
Dim CountAll As Long
Dim CountXL As Long
Dim CustomerName As String

ActiveSheet.Range("A1").Activate

CountAll = ActiveSheet.Range("A35")

For j = 1 To CountAll
i = 2

CountXL = Cells(i, j).Value

For i = 1 To CountXL
CustomerName = Cells(1, j).Value
'MsgBox CustomerName
Cells(i + 2, j).FormulaArray = "=IFERROR(INDEX(Sheet2!$A:$B,SMALL(IF(Sheet2!$A:$A=CustomerName,ROW(Sheet2!$A:$A)),ROW(1:1))*1,2),0)"
Next i

Next j

End Sub

There is no error; however i need This part fixed so it references the value instead of the actual word inside the formula:
IF(Sheet2!$A:$A=CustomerName

In your case, use below:

Cells(i + 2, j).FormulaArray = "=IFERROR(INDEX(Sheet2!$A:$B,SMALL(IF(Sheet2!$A:$A=""" & CustomerName & """,ROW(Sheet2!$A:$A)),ROW(1:1))*1,2),0)"

in general, if you need concat string use "formula_par21""" & value & """formula_part2 , if it's number - without double quotes, like "formula_par21" & value & "formula_part2

"" in VBA = " in string variable

Cells(i + 2, j).FormulaArray = "=IFERROR(INDEX(Sheet2!$A:$B,SMALL(IF(Sheet2!$A:$A=""""" & CustomerName & """"",ROW(Sheet2!$A:$A)),ROW(1:1))*1,2),0)"

You gotta double the "" in the Formulas in VBA --> "" = """"

Here is a simple example why you might get the errors:

Excel Formula:

=If(A1<>"";A1;B1)

VBA Formula

"=IF(A1<>"""",A1,B1)"

so i would recommend you to try this:

Cells(i + 2, j).FormulaArray = "=IFERROR(INDEX(Sheet2!$A:$B,SMALL(IF(Sheet2!$A:$A=""""" & CustomerName & """"",ROW(Sheet2!$A:$A)),ROW(1:1))*1,2),0)"

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