简体   繁体   English

在excel单元格中定义数组,并在excel数组公式中使用该单元格

[英]define array in excel cell and use that cell in excel array formula

I have an excel cell A1 having cell content {"Q15","R15","S15"}. 我有一个具有细胞含量{“Q15”,“R15”,“S15”}的excel细胞A1。

How can I use A1 cell in array formula in excel? 如何在excel中使用数组公式中的A1单元格?

I have used this formula: 我用过这个公式:

=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,{"Q15","R15","S15"}))

the above formula works fine. 上面的公式很好。

but when replaced with A1, it gives 0. And formula becomes 但是当用A1代替时,它会给出0.并且公式变为

=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,A1))

How can I use A1 so that the resulting formula contains the actual array? 如何使用A1以使得结果公式包含实际数组?

The problem you have here is that Excel is reading {"Q15","R15","S15"} from A1 as a String ( ="{""Q15"",""R15"",""S15""}" ), not as an array. 你在这里遇到的问题是Excel正在从A1读取{"Q15","R15","S15"}作为字符串( ="{""Q15"",""R15"",""S15""}" ),而不是数组。

You can get around this using MID and TRIM to artificially split the string via a SUMPRODUCT 可以使用MIDTRIM通过SUMPRODUCT人为地分割字符串

=SUMPRODUCT(COUNTIFS('sheet1'!$D$2:$D$838, "<>NA", 'sheet1'!$E$2:$E$838, TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1, """,""", REPT(" ", 99)), "{""", ""), """}", ""), 99*ROW(A1:INDEX(A:A, 1+LEN(A1)-LEN(SUBSTITUTE(A1, ",", ""))))-98, 60))))

The "magic" bit here is the rather convoluted line below 这里的“神奇”位是下面相当复杂的一行

TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,""",""",REPT(" ",99)),"{""",""),"""}",""),99*Row(A1:INDEX(A:A,1+Len(A1)-Len(SUBSTITUTE(A1,",","")))-98,60)) TRIM(MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,“”“,”“”,REPT(“”,99)),“{”“”,“”),“”“}”,“”),99 *行(A1:INDEX(A:A,1 + LEN(A1)-LEN(SUBSTITUTE(A1, “”, “”))) - 98,60))

Turns {"Q15","R15","S15"} into Q15 , R15 and S15 , separated by 99 spaces. {"Q15","R15","S15"}变为Q15R15S15 ,相隔99个空格。 It then counts how many commas are in A1 , and (that many times) takes 60 characters (starting at position 1 the first time, then position 100 the second time, then position 199, et cetera) and trims the spaces - this gives an array {"Q15","R15","S15"} 然后它计算A1有多少逗号,并且(多次)占用60个字符(第一次从位置1开始,然后第二次从位置100开始,然后是位置199,等等)并修剪空格 - 这给出了数组{"Q15","R15","S15"}

So, as Tim Williams says in comments, you might be better off using VBA. 因此,正如蒂姆·威廉姆斯在评论中所说的那样,使用VBA可能会更好。 A basic User Defined Function to split the array like this would work: 像这样拆分数组的基本用户定义函数可以工作:

Public Function SplitArray(Text As String) As Variant
    'If we error, show #NA!
    SplitArray = CVErr(xlErrNA)
    On Error GoTo FunctionErred
    'Split the array
    If Left(Text, 1) = "{" And Right(Text, 1) = "}" Then
        SplitArray = Split(Replace(Mid(Text, 2, Len(Text) - 2), """", ""), ",")
    Else
        SplitArray = Text
    End If
FunctionErred:
End Function

Giving 给予

=SUM(COUNTIFS('sheet1'!$D$2:$D$838,"<>NA",'sheet1'!$E$2:$E$838,SplitArray(A1)))

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

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