Alt enter excel vba

bmcvicker

New Member

Joined
Nov 25, 2008
Messages
2


  • #1

Hi there,

I’ve been struggling for a few hours now trying to sort this problem. I have multiple rows of data that have been entered into excel cells using Alt + Enter. This has created a situation where I have multiple rows in each cell. I need to separate these out and I’ve tried various extraction methods but none of them (Text to Columns, Replace or VBA) seem to recognise the character that Alt + Enter is using.
It works, if I use a modified excel formula for finding first word, last word, nth word etc from a cell and I insert an Alt + Enter for the character I want to find. For the nth word I need to add a whole section to the formula and it is getting too cumbersome especially with Alt + Enter breaks through it and up to 15 rows in a cell. There is a VBA function that could do the trick (replacing the spaces it looks for with Alt + Enters) but it doesn’t recognise the Alt + Enters as Chr(13)’s or vbCrLf’s in the spreadsheet.

Any ideas on how I can find these Alt + Enters in VBA and use them in the function or replace them so I can separate this data out?

Thanks,
Brian

Excel Facts

Can you sort left to right?

To sort left-to-right, use the Sort dialog box. Click Options. Choose «Sort left to right»

Blade Hunter

Blade Hunter

Well-known Member

Joined
Mar 13, 2008
Messages
3,147


  • #2

13 I believe

Edit: Make that 10

Go into Excel, enter it into a cell

Type this in the debug window of the VBE:

?asc(activecell.Text)

Excel can recognise this in formulas too:

=SUBSTITUTE(A1,CHAR(10),»») will replace the Alt-Enter’s with nothing.

Last edited: Nov 25, 2008

Andrew Fergus

Andrew Fergus

MrExcel MVP

Joined
Sep 9, 2004
Messages
5,452
Office Version
  1. 365
  2. 2021
  3. 2016
Platform
  1. Windows


  • #3

Hi and welcome to MrExcel!

Alt+Enter = character 10.

To substitute these out of the text using an Excel formula, try this:
=SUBSTITUTE(A1,CHAR(10),»,»)
where the raw data is in cell A1.

Andrew

bmcvicker

New Member

Joined
Nov 25, 2008
Messages
2


  • #4

Thanks Andrew, CHAR(10) worked in the formula.

Cheers,
Brian

Peter_SSs

Peter_SSs

MrExcel MVP, Moderator

Joined
May 28, 2005
Messages
59,294
Office Version
  1. 365
Platform
  1. Windows


Similar threads

This post will explain that how to find Alt + Enter characters or line breaks in the range of cells and then replace it with space character or other specific characters in excel.

When you want to create a line break in a cell in excel, you just need to press Alt + Enter keys. So you can insert one or more line breaks in a cell to make the contents easier to read.

You can use the Find and Replace function to replace all Alt +Enter with space character. Or you can use the VBA Macro code to achieve the same result quickly.

Find and Replace Line Break (Alt+Enter) with Space using Find and Replace Function


If you want to find a line break and then replace it with a space character, just do the following steps:

#1 select the cells that you want to find and replace

find replace linebreak1

#2 go to HOME tab, click Find&Select command under Editing group, and click Replace… menu from the drop down list or just press Ctrl +H keys to open the Find and Replace dialog box.

find replace linebreak2

#3 click in the Find what text box, press Ctrl +J to enter the line break.

#4 click in the Replace with text box, type a space character or other characters as you need.

find replace linebreak3

#5 Click Replace All to replace the line breaks with space characters.

find replace linebreak4

Find and Replace Line Break with Space using VBA


You can write an Excel VBA Macro to find alt +enter and then replace it with a space character, following these steps:

#1 click on “Visual Basic” command under DEVELOPER Tab.

Get the position of the nth using excel vba1

#2 then the “Visual Basic Editor” window will appear.

#3 click “Insert” ->”Module” to create a new module.

convert column number to letter3

#4 paste the below VBA code into the code window. Then clicking “Save” button.

find replace linebreak5

Sub ReplaceAltEnter()
    Dim fRange As Range
    On Error Resume Next
    Set fRange = Application.InputBox("Select the range of Cells:", "Replace Alt Enter", Selection.Address, , , , , 8)
    If fRange Is Nothing Then Exit Sub
    fRange.WrapText = False
    fRange.Replace Chr(10), " ", xlPart, xlByColumns
End Sub

#5 back to the current worksheet, then run the above excel macro. Click Run button.

find replace linebreak6

#6 select the range of cells that you want to find, click OK.

find replace linebreak7

#7 Let’s see the result.

find replace linebreak8

I have a VBA Macro for relacing a word with another one in Excel.

Call CharactersReplace(xRg, "Test1", "Test2", True)

It is working nicely but I want to do Alt+Enter on the cell of Excel (instead of Test2).

Literally I want to do the line wrap within the cell.

Example:

From: Hey How are you? Test1 Bla Bla
To: Hey How are you?
Bla Bla

There is a code on VBA to do it? I tried to do CHA(10) etc. but they are not working.

asked Mar 20, 2019 at 13:10

Michelozzo8's user avatar

2

The vbLf or Chr(10) is the equivalent of a line break whithin a cell. So the following should work:

Call CharactersReplace(xRg, "Test1", vbLf, True)

Also make sure that .WrapText of that cell is True.

eg: Range("A1").WrapText = True otherwise you will insert a line break but won’t see it.

answered Mar 20, 2019 at 13:22

Pᴇʜ's user avatar

PᴇʜPᴇʜ

56k9 gold badges49 silver badges73 bronze badges

Alt Enter is known as a manual line break in Excel. It’s what you use when you want to have text show in multiple lines regardless the width of the column. But sometimes you need to insert or remove line breaks (Alt Enter) on a high level. Meaning that there are multiple line breaks you want to insert or remove at once. Firstly, let’s look at the Remove or Replace multiple Line Breaks at once.

Remove or Replace Line Breaks in Excel

The Remove and Replace part can be done with the Find and Replace tool, where the only trick you have to know, is to use the Ctrl+J or Alt+0010 (the 0010 has to be typed in the numeric part of the keyboard) combination in the Find Box.

REMOVE, REPLACE OR SEPARATE BY LINE BREAKS (ALT + ENTER) INCLUDING VBA

This gives you a blinking dot that represents a cursor that has dropped by one line and then if you leave the Replace with empty, you will remove the line breaks and if you put Space (or any character you want) in the Replace with box, all your line breaks will be replaced by spaces (or your selected character).

Remove or Replace Line Breaks (Alt+Enter) in Excel with VBA

First of all, this code works with the Selection, so it will only execute on the selected cells. And the other thing is, this code turns off the Wrap Text command. More or less this is done so you can easily see the effect of the code but it’s also there for practical reasons. If you don’t like that, just comment out the second line of code. The code itself is very simple and actually utilizes the Excels Find and Replace Tool. The Remove VBA is very simple…

 Sub RemoveLineBreak()
Selection.WrapText = False 'Removing Wrap Text
Selection.Replace What:=Chr(10), Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
End Sub

The replace code is identical except for the Your Text Here part. So just replace that with the desired replacement text

 Sub ReplaceLineBreak()
Selection.WrapText = False 'Removing Wrap Text
Selection.Replace What:=Chr(10), Replacement:="Your text here", LookAt:=xlPart, _
    SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
End Sub

But now for the crown jewel of this post… The Separate By line breaks.

Separate By Line Breaks (Alt+Enter) in Excel

The easiest way in Excel is to use the Data/Text to Columns command.

REMOVE, REPLACE OR SEPARATE BY LINE BREAKS (ALT + ENTER) INCLUDING VBA

Where in Step 2 of the Wizard, you select Other and again, either use the Ctrl+J or Alt+0010 key combination to insert the line break (Alt+Enter). Same as in the previous samples, this will give you the blinking cursor dot… But in the data preview you can easily see that this will result in more than One column. Keep in mind that this command will behave the same as it always does, even if you separate by line breaks. It will overwrite any data in those columns.

REMOVE, REPLACE OR SEPARATE BY LINE BREAKS (ALT + ENTER) INCLUDING VBA

Click Finnish and you get

REMOVE, REPLACE OR SEPARATE BY LINE BREAKS (ALT + ENTER) INCLUDING VBA

Simply brilliant but still over 4 clicks J. That brings us to the VBA part…

Separate By Line Breaks in Excel with VBA

So the code just simulates the above command (Data/Text To Columns) but with less effort on your part. It’s very important that you realize, that this code (although in full working state) is only the center piece, there’s a lot of error handling and loss of data warnings that you must put in place for this code to be “all it can be”. It goes without saying that in our AddIn, all those safeties are in place. The only safety in this case is some error handling if the data would have to be written out of bounds. Here is the code.

       
Sub SeperateBy()
On Error Resume Next
    Application.DisplayAlerts = False
    Set Rng2 = Range(Selection.Item(1).Address)
        Selection.TextToColumns Destination:=Rng2, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Other:=True, OtherChar:=Chr(10), FieldInfo _
        :=Array(1, 1), TrailingMinusNumbers:=True
                        If Err.Number = 1004 Then
                            ui = MsgBox("You will now stop the execution of the code", vbOKOnly)
                                If ui = vbOK Then
                                Application.ScreenUpdating = True
                                Exit Sub
                                End If
                        End If
Application.DisplayAlerts = True
End Sub

And with this, we are one step closer to eternal happiness.

And also, if there is a command or a functionality that you miss in Excel, write it in the comment section bellow or give me a shout over the contact form, and I will write about it in one of the next posts on Excel Unplugged. J.

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

Доброго времени суток!

На листе в ячейке A1 запись в две строки. При ее записи весь текст сливается в одну строчку.
Как сделать так, чтобы сохранить данные построчно…. может быть в массиве? а затем после обработки вставить в другую ячейку в таком же виде в две строки обратно…

 

Jack Famous

Пользователь

Сообщений: 10846
Регистрация: 07.11.2014

OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome

Пока попробуйте в формате ячейки или на ленте поставить галочку/нажать кнопку «переносить текст».

Изменено: Jack Famous16.01.2018 14:28:47

Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

Jack Famous, ладно, понял в чем беда, сначала

пошагово, что я хочу
1) На листе в ячейке A1 запись многострочная через перенос alt+enter (так надо)
2) в vba есть переменная A, в которую я записываю ячейку A1 (при этом текст из многострочного превращается в одну строку — а мне надо, чтобы данная структура сохранялась)
3) какие-то действия с данными
4) нужно вывести в ячейку A2 отредактированную переменную A, но при этом должна быть сохранена первоначальная структура с переносами внутри ячейки (vbLf)

 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

#4

16.01.2018 13:48:12

Уважаемый Boris05036! В Excel замечательная среда программирования, в которой можно очень быстро проверять различные гипотезы, в частности Вашу.

Код
Sub test()
  Dim a
  a = Range("A1")
  Range("A2") = a
End Sub

Мы видим, что в случае, когда ячейка A1 является многострочной, ячейка A2 также является многострочной (знак vblf никуда не исчезает).

Владимир

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

sokol92, спасибо, вы прав (видимо я уже перегрелся), я понял, но проблема остается, дополню

в итоге данная ячейка уходит затем в htmlbody (outlook) и видимо для него vbLf вещь непонятная
если это возможно в рамках данной темы, то прошу подсказать, как мне в сообщении html сохранить это?

В сообщение вставка происходит с использованием переменной vba

Изменено: Boris0503616.01.2018 13:52:57

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Excel, он, конечно, умный, но самостоятельно параметр «перенос текста» в ячейках изменять не умеет.  :)

 

Апострофф

Пользователь

Сообщений: 720
Регистрация: 06.04.2015

#7

16.01.2018 14:15:29

Цитата
Boris05036 написал:
для него vbLf вещь непонятная

Код
s=replace(s,vblf,vbcr)


или

Код
s=replace(s,vblf,vbcrlf)

один из вариантов(а может и оба) он должен понять…

Изменено: Апострофф16.01.2018 14:16:05

 

Boris05036

Пользователь

Сообщений: 42
Регистрация: 12.03.2016

#8

16.01.2018 14:21:26

Цитата
Апострофф написал:
один из вариантов(а может и оба) он должен понять…

ни один не понял, но спасибо за идею, как-то я сразу недоехал, переменная ведь все равно текстовая, так работает

Код
s=replace(s,vbLf, "<br>")
 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

#9

16.01.2018 14:26:56

Для более сложных случаев есть метод

PublishObjects.Add

Владимир

Часто требуется внутри одной ячейки Excel сделать перенос текста на новую строку. То есть переместить текст по строкам внутри одной ячейки как указано на картинке. Если после ввода первой части текста просто нажать на клавишу ENTER, то курсор будет перенесен на следующую строку, но другую ячейку, а нам требуется перенос в этой же ячейке.

Перенос строки в Excel в одной ячейке

Это очень частая задача и решается она очень просто — для переноса текста на новую строку внутри одной ячейки Excel необходимо нажать ALT+ENTER (зажимаете клавишу ALT, затем не отпуская ее, нажимаете клавишу ENTER)

Содержание

  • 1 Как перенести текст на новую строку в Excel с помощью формулы
    • 1.1 Как в Excel заменить знак переноса на другой символ и обратно с помощью формулы
    • 1.2 Как поменять знак переноса на пробел и обратно в Excel с помощью ПОИСК — ЗАМЕНА
    • 1.3 Как поменять перенос строки на пробел или наоборот в Excel с помощью VBA
    • 1.4 Коды символов для Excel

Как перенести текст на новую строку в Excel с помощью формулы

Иногда требуется сделать перенос строки не разово, а с помощью функций в Excel. Вот как в этом примере на рисунке. Мы вводим имя, фамилию и отчество и оно автоматически собирается в ячейке A6

Как сделать переност строки в Excel с помощью формулы

Для начала нам необходимо сцепить текст в ячейках A1 и B1 (A1&B1), A2 и B2 (A2&B2), A3 и B3 (A3&B3)

После этого объединим все эти пары, но так же нам необходимо между этими парами поставить символ (код) переноса строки. Есть специальная таблица знаков (таблица есть в конце данной статьи), которые можно вывести в Excel с помощью специальной функции СИМВОЛ(число), где число это число от 1 до 255, определяющее определенный знак.
Например, если прописать =СИМВОЛ(169), то мы получим знак копирайта ©

Нам же требуется знак переноса строки, он соответствует порядковому номеру 10 — это надо запомнить.
Код (символ) переноса строки — 10
Следовательно перенос строки в Excel в виде функции будет выглядеть вот так СИМВОЛ(10)

Примечание: В VBA Excel перенос строки вводится с помощью функции Chr и выглядит как Chr(10)

Итак, в ячейке A6 пропишем формулу

=A1&B1&СИМВОЛ(10)&A2&B2&СИМВОЛ(10)&A3&B3 

В итоге мы должны получить нужный нам результат.
Обратите внимание! Чтобы перенос строки корректно отображался необходимо включить «перенос по строкам» в свойствах ячейки.
Для этого выделите нужную нам ячейку (ячейки), нажмите на правую кнопку мыши и выберите «Формат ячеек…»
формат ячейкив Excel

В открывшемся окне во вкладке «Выравнивание» необходимо поставить галочку напротив «Переносить по словам» как указано на картинке, иначе перенос строк в Excel не будет корректно отображаться с помощью формул.

Перенос по строкам в формате ячеек

Как в Excel заменить знак переноса на другой символ и обратно с помощью формулы

Можно поменять символ перенос на любой другой знак, например на пробел, с помощью текстовой функции ПОДСТАВИТЬ в Excel

Как заменить перенос строки на пробел в Excel

Рассмотрим на примере, что на картинке выше. Итак, в ячейке B1 прописываем функцию ПОДСТАВИТЬ:

=ПОДСТАВИТЬ(A1;СИМВОЛ(10);» «)

A1 — это наш текст с переносом строки;
СИМВОЛ(10) — это перенос строки (мы рассматривали это чуть выше в данной статье);
» » — это пробел, так как мы меняем перенос строки на пробел

Если нужно проделать обратную операцию — поменять пробел на знак (символ) переноса, то функция будет выглядеть соответственно:

=ПОДСТАВИТЬ(A1;» «;СИМВОЛ(10))

Напоминаю, чтобы перенос строк правильно отражался, необходимо в свойствах ячеек, в разделе «Выравнивание» указать «Переносить по строкам».

Как поменять знак переноса на пробел и обратно в Excel с помощью ПОИСК — ЗАМЕНА

Бывают случаи, когда формулы использовать неудобно и требуется сделать замену быстро. Для этого воспользуемся Поиском и Заменой. Выделяем наш текст и нажимаем CTRL+H, появится следующее окно.

Заменить код переноса строки на пробел с помощью Поиск-Замена в Excel

Если нам необходимо поменять перенос строки на пробел, то в строке «Найти» необходимо ввести перенос строки, для этого встаньте в поле «Найти», затем нажмите на клавишу ALT, не отпуская ее наберите на клавиатуре 010 — это код переноса строки, он не будет виден в данном поле.

После этого в поле «Заменить на» введите пробел или любой другой символ на который вам необходимо поменять и нажмите «Заменить» или «Заменить все».

Кстати, в Word это реализовано более наглядно.

Если вам необходимо поменять символ переноса строки на пробел, то в поле «Найти» вам необходимо указать специальный код «Разрыва строки», который обозначается как ^l
В поле «Заменить на:» необходимо сделать просто пробел и нажать на «Заменить» или «Заменить все».

Заменить перенос строки на пробел с помощь Найти Заменить в Excel

Вы можете менять не только перенос строки, но и другие специальные символы, чтобы получить их соответствующий код, необходимо нажать на кнопку «Больше >>», «Специальные» и выбрать необходимый вам код. Напоминаю, что данная функция есть только в Word, в Excel эти символы не будут работать.

Специальные символы для поиск-замены

Как поменять перенос строки на пробел или наоборот в Excel с помощью VBA

Рассмотрим пример для выделенных ячеек. То есть мы выделяем требуемые ячейки и запускаем макрос

1. Меняем пробелы на переносы в выделенных ячейках с помощью VBA

Sub ПробелыНаПереносы()
For Each cell In Selection
cell.Value = Replace(cell.Value, Chr(32), Chr(10))
Next
End Sub

2. Меняем переносы на пробелы в выделенных ячейках с помощью VBA

Sub ПереносыНаПробелы()
For Each cell In Selection
cell.Value = Replace(cell.Value, Chr(10), Chr(32))
Next
End Sub

Код очень простой Chr(10) — это перенос строки, Chr(32) — это пробел. Если требуется поменять на любой другой символ, то заменяете просто номер кода, соответствующий требуемому символу.

Коды символов для Excel

Ниже на картинке обозначены различные символы и соответствующие им коды, несколько столбцов — это различный шрифт. Для увеличения изображения, кликните по картинке.

Коды символов

Понравилась статья? Поделить с друзьями:
  • An informal word for also
  • Also first word sentence
  • An informal word for a conversation
  • Alsm excel to internal table
  • An explanation of the meaning of a word is known as