繁体   English   中英

在Excel VBA中引用公式数组内的字符串

[英]Referencing a string inside a Formula Array in Excel VBA

需要一些帮助引用索引公式数组中的字符串

我的代码如下:

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

没有错误; 但是我需要修复此部分,以便它引用值而不是公式中的实际单词:
IF(Sheet2!$ A:$ A = 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)"

通常,如果需要concat字符串,请使用"formula_par21""" & value & """formula_part2 (如果为数字)-不带双引号,例如"formula_par21" & value & "formula_part2

VBA中的“” =字符串变量中的“

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)"

您必须将VBA公式中的“”加倍->“” =“”“”

这是一个简单的示例,为什么会出现错误:

Excel公式:

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

VBA公式

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

所以我建议您尝试一下:

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)"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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