I've got a whole bunch of cells containi开发者_开发技巧ng arbitrary length arrays stored as semicolon-delimited strings, ranging in length from 1 to 65 entries, like:
- pcmsh15(232);pcmsh16(232);pcmsh17(136);
- pcmsh12(40);
- pcmsh12(40);
- pcmsh12(5);pcmsh15(20);
I want a way to sum up the numbers in the parenthesis in Excel 2010 without using VBA, keeping in mind that they are arbitrary length strings, each contained in their own cell.
I've currently got a VBA function that I wrote that sums the numbers in parenthesis, but it's slowing my spreadsheet down. I know I can use Excel's SUBSTITUTE function to turn the semi-colon delimited arrays into something resembling Excel's internal array format, like
="{"&SUBSTITUTE([@[data]],";",",")&"}"
But unfortunately, Excel won't parse that as an array in SUM or COUNTIF, only as a string. One workaround I found makes a named range that references the cell with a string-formatted array, but since I also have an arbitrary number of these arrays in cells, I can't go naming every single cell.
Is something like this possible in "pure" excel functions?
You can actually do this with no VBA involved. The method is kind of ridiculous, though. But, just for fun...
In cell B4
I put one of the strings you want to "parse":
B4: pcmsh15(232);pcmsh16(232);pcmsh17(136);
Then I put the following formulas in the cells indicated:
B6: =SUBSTITUTE(B4,"pcmsh", """dummy")
B8: =SUBSTITUTE(B6,"(",""";")
B10: =SUBSTITUTE(B8,")","")
B12: =MID(B10, 1, LEN(B10)-1)
B14: ="{"&B12&"}"
That transforms the starting text into a text representation of a legal Excel array:
B14: {"dummy15";232;"dummy16";232;"dummy17";136}
You can make Excel evaluate that string and return an actual array with the following trick. Create a named formula that we'll call eval_left
. Make sure cell C14
is selected when you create the named formula:
=EVALUATE(B14)
Note that the formula uses a relative reference, so if you use that name from a cell other than C14
, you'll see that the B14
has changed to whatever cell is just to the left.
This uses the old Excel 4 macro function EVALUATE
, which takes a string and returns the value that that string represents. Now we can put a final formula in cell C14
:
C14: =SUM(eval_left)
Since SUM
ignores non-numeric strings, you get the answer you want, with no VBA. (You do still get the macro warning though, because of the use of EVALUATE
.)
Like I said, I consider this a just-for-fun curiousity. You're way better off using VBA for stuff like this.
EDIT:
In the unlikely event you wanted to actually do something like this, you'd run into the length limit of what EVALUATE
can handle. You'd have to chop up your longer strings into less than 65 values, not use "dummy", etc., but it would still be doable.
精彩评论