簡體   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