Как выбрать первый номер в ячейке в Excel?

1128
jeff

У меня есть таблица, в которой хранится как число, так и некоторый текст в ячейке, и я хочу выполнить арифметическую операцию на основе чисел. Итак, мой стол выглядит так:

Number1 | Number2 | Product 2 | 3 | 6 3 (some text) | 40 | 120 4 | 5 (here too) | 20 

Таким образом, при наличии этих уродливых текстов, я все еще хочу иметь возможность производить колонку 3 автоматически. Я думаю, мне нужна функция, которая анализирует подстроку до первого нечислового символа в число. Могу ли я сделать это с помощью Excel?

PS: номера могут иметь более 1 цифры. Можно с уверенностью предположить, что они являются целыми числами, но было бы неплохо увидеть решение, которое применимо и к плавающим точкам :)

Спасибо,

1
Конечно, идеальное решение - не смешивать числа и текст в ячейке, которую вы хотите использовать для арифметики. Разве разделение первых двух столбцов исключено? fixer1234 7 лет назад 0
Под разделением вы имеете в виду разделение чисел и текста? Ну, это, конечно, вариант (возможно, элегантный :)), другой может использовать комментарии для хранения текстовой информации, но мне все еще интересно, смогу ли я справиться с этим программно. jeff 7 лет назад 0

2 ответа на вопрос

3
Scott Craner

To get the numbers if they are in the beginning of the string we can use this:

=MID(A2,1,AGGREGATE(14,6,SEARCH("}}}",SUBSTITUTE(A2,,"}}}",LEN(A2)-LEN(SUBSTITUTE(A2,,"")))),1)) 

as our base formula, This will find the end of the number and return that as the end of the MID() Function.

There is a lot going on here:

SUBSTITUTE(A2,,"}}}",LEN(A2)-LEN(SUBSTITUTE(A2,,""))) As this part iterates through the numbers it is replacing the last instance of each number with }}}.

The third criterion of SUBSTITUTE is the instance. We find the number of instances with the LEN(A2)-LEN(SUBSTITUTE(A2,,"")). It iterates through the numbers and replaces each one at a time with nothing. It then finds the difference in length of the original string and the new one.

So in the case of A2 when it iterates to the 2 it finds 2 and the outer Substitute replaces the last one with }}}. This is just a temprorary place holder.

The Aggregate function is a multi function function. The 14 tells the funtions we are using the Large() function. The 6 tells the function to ignore errors. This is important in that many of the iteration will not find anything and return an error.

With the 1 at the end it tells the function we want the highest return from the Search function which searches for those temporary }}} that are placed through iteration on the last instance of each number.

So the Aggregate returns the max number found. Which we pass to the length criterion in the Mid function.

So we now have found the number at the front of the string.

So we can multiply two of these together to get the desired output(Any math function will turn the returned string into a number):

=MID(A2,1,AGGREGATE(14,6,SEARCH("}}}",SUBSTITUTE(A2,,"}}}",LEN(A2)-LEN(SUBSTITUTE(A2,,"")))),1))*MID(B2,1,AGGREGATE(14,6,SEARCH("}}}",SUBSTITUTE(B2,,"}}}",LEN(B2)-LEN(SUBSTITUTE(B2,,"")))),1)) 

enter image description here

One Caveat The Aggregate function was introduced in Excel 2010. It may not work with older versions.

If you have an older version you will need to use this longer formula:

=MID(A2,1,MAX(IF(ISNUMBER(SEARCH("}}}",SUBSTITUTE(A2,,"}}}",LEN(A2)-LEN(SUBSTITUTE(A2,,""))))),SEARCH("}}}",SUBSTITUTE(A2,,"}}}",LEN(A2)-LEN(SUBSTITUTE(A2,,"")))))))*MID(B2,1,MAX(IF(ISNUMBER(SEARCH("}}}",SUBSTITUTE(B2,,"}}}",LEN(B2)-LEN(SUBSTITUTE(B2,,""))))),SEARCH("}}}",SUBSTITUTE(B2,,"}}}",LEN(B2)-LEN(SUBSTITUTE(B2,,""))))))) 

It does roughly the same as the one above accept it must test for the errors first before finding the max.

Можете ли вы добавить краткое объяснение того, как это работает? fixer1234 7 лет назад 0
@ fixer1234 исправил это. Смотрите редактировать. Scott Craner 7 лет назад 0
Извините, я попросил объяснения. Это заставило мой мозг взорваться. :-) Но похоже, что это работает, так что +1. fixer1234 7 лет назад 0
@ fixer1234 рад, что ты это сделал, я понял, что моя первая попытка была ошибочной и нуждалась в переделке. Scott Craner 7 лет назад 0
@ fixer1234, если вы думаете, что это было сложно, смотрите здесь: http://stackoverflow.com/questions/37870970/adjust-project-hours-based-on-priority/37903416#37903416 Я не собираюсь анализировать тот, который потребуется книга. Scott Craner 7 лет назад 0
1
fixer1234

Assuming the number is always separated from any text by a space, you could use something like this. Say your example has data starting in A2, so your first result in C2 would ordinarily look like:

=A2*B2 

We need to replace the simple cell references with a formula that treats the source cell as a number if it's only a number, but extracts the number if there's also text. So C2 would become:

=IF(ISNUMBER(A2),A2,LEFT(A2,FIND(" ",A2)-1)) * IF(ISNUMBER(B2),B2,LEFT(B2,FIND(" ",B2)-1)) 

If the source cell isn't a number, it finds the first space and returns the characters before it. Technically, what it returns is a text value containing digits, but Excel is smart enough to treat it as a number in calculating the product (no need to nest that inside another function to convert it to a number). And note that if the number is floating point, this will still work.

Caveat: This relies on "clean" source data, i.e., either a numeric entry, or a text entry where it starts with a number which is followed by a space. If there is a cell that doesn't conform to that, you would need to either clean up the data or include some form of error checking. The best solution would be to split the two data columns so that any text is in a separate cell.

Это здорово, спасибо! Но первый нечисловой символ может не быть пробелом. Интересно, можем ли мы использовать какой-либо поиск по шаблону в функции `НАЙТИ`? jeff 7 лет назад 0
Какие это могут быть символы, кроме пробела? fixer1234 7 лет назад 0
Ну, я не хочу определять белый список, поэтому я ищу дикий поиск, который просто исключает числа (и, возможно, `.` и`, `). jeff 7 лет назад 0
Это, конечно, становится намного сложнее, чем A2 * B2. :-) Мне придется подумать о способе включения регулярных выражений. Если существует слишком много существующих данных для очистки вручную, вы бы хотели, чтобы что-то в этом духе автоматизировало процесс, во всяком случае, чтобы разделить не-числа в другую ячейку. Если вам когда-нибудь понадобится объяснить лист кому-то другому или поддержать его позже, A2 * B2 намного проще, чем иметь смысл длинной формулы, которая предназначена только для обработки значений ячеек. fixer1234 7 лет назад 0

Похожие вопросы