Vba excel текст в столбец

In this Article

  • Text to Columns
    • TextToColumns Syntax
    • Converting Text to Columns

This tutorial will show you how to convert string of text in a single cell to multiple columns using the Range TextToColumns method in VBA

Text to Columns

The Range.TextToColumns method in VBA is a powerful tool for cleaning up data that has been imported from text or csv files for example.

Consider the following worksheet.

vba texttocol quotes

The data has come into Excel all in one column, and is separated by quotation marks.

You can use the Range TextToColumns method to separate this data into columns.

TextToColumns Syntax

expression.TextToColumns (DestinationDataTypeTextQualifierConsecutiveDelimiterTabSemicolonCommaSpaceOtherOtherCharFieldInfoDecimalSeparatorThousandsSeparatorTrailingMinusNumbers)

vba texttocol syntax

Expression

This is the Range of cells you wish to split – eg: Range(“A1:A23”).

All of the arguments in the TextToColumns method are optional (they have square brackets around them).

Destination

Where you want the result to be put – often you override the data and split it in the same location.

DataType

The type of text parsing you are using – it can either be xlDelimited (default if omitted), or xlFixedWidth.

TextQualifier

If you have quotation marks (single or double) around each field in the text that you are splitting, you need to indicate if they are single or double.

ConsequtiveDelimiter

This is either true or false and tells VBA to consider 2 of the same delimiters together as if it were 1 delimiter.

Tab

This is either True of False, the Default is False – this tells VBA that the data is delimited by a Tab.

Semicolon

This is eitherTrue of False, the Default is False – this tells VBA that the data is delimited by a Semicolon.

Space

This is either True of False, the Default is False – this tells VBA that the data is delimited by a Space.

Other

This is either True of False, the Default is False.  If you set this to True, then the next argument, OtherChar needs to be specified.

OtherChar

This is the character by which the text is separated (ie: ^ or | for example).

FieldInfo

This is an array containing information about the type of data that is being separated.  The first value in the array indicates the column number in the data, and the second value indicates the constant that you are going to use to depict the data type you require.

An example of for 5 columns with data types of text, numbers and dates could be:

Array(Array(1, xlTextFormat), Array(2, xlTextFormat), Array(3, xlGeneralFormat), Array(4, xlGeneralFormat), Array(5, xlMDYFormat))

Another way of setting this out is:

Array(Array(1, 2), Array(2, 2), Array(3, 1), Array(4, 1), Array(5, 3))

The numbers in the second column are the values of the constants where the constant xlTextFormat has a value of 2, the xlGeneralFormat (default) has a value of 1 and the xlMDYFormat has a value of 3.

DecimalSeparator

You can specify the decimal separator that VBA must use to if there are numbers in the data. If omitted, it will use the system setting, which is usually a period.

ThousandsSeparator

You can specify the thousands separator that VBA must use to if there are numbers in the data. If omitted, it will use the system setting, which is usually a comma.

TrailingMinusNumbers

This argument is largely for compatibility for data that is generated from older systems where a minus sign was often after the number and not before. You should set this to True if negative numbers have the minus sign behind them.  The Default is False.

Converting Text to Columns

The following procedure will convert the Excel data above into columns.

Sub TextToCol1()
   Range("A1:A25").TextToColumns _
   Destination:=Range("A1:A25"), 
   DataType:=xlDelimited, _
   TextQualifier:=xlDoubleQuote, _
   ConsecutiveDelimiter:=True, _
   Tab:=False, _
   Semicolon:=False, _
   Comma:=False, 
   Space:=True, _
   Other:=False, _
   FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), _
   DecimalSeparator:="." , _
   ThousandsSeparator:=",", _ 
   TrailingMinusNumbers:=True
End Sub

In the above procedure we have filled in all of the parameters.  However, many of the parameters are set to false or to the default setting and are not necessary. A cleaner version of the above procedure is set out below. You need to use the parameter names to indicate which parameters we are using.

Sub TextToCol2()
  Range("A1:A25").TextToColumns _
  DataType:=xlDelimited, _
  TextQualifier:=xlDoubleQuote, _
  ConsecutiveDelimiter:=True, _
  Space:=True,
End Sub

There are only 4 parameters that are actually required – the data is delimited by a double quote, you want consecutive quotes treated as one and the data is separated by a space!

For an even speedier line of code, we could omit the parameter names, but then we would need to put in commas to save the place of the parameter. You only need to put information as far as the last parameter you are using – in this case the Space that separates the data which is the 8th parameter.

Sub TextToCol3()
   Range("A1:A25").TextToColumns , xlDelimited, xlDoubleQuote, True, , , , True
End Sub

Once you run the any of the procedures above, the data will be separated as per the graphic below.

vba texttocol split

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

 

Alex D

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

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

Здравствуйте,
Может у кого завалялось решение/макрос по переводу данных из строки в столбец (список).
Пример прикреплен.
Спасибо большое!

Прикрепленные файлы

  • test_1.xlsx (13.85 КБ)

 

buchlotnik

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

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

Excel 365 Бета-канал

#2

11.10.2019 16:20:09

вариант PQ:

Код
 let
    from = Excel.CurrentWorkbook(){[Name="Таблица1"]}[Content],
    replace = Table.ReplaceValue(from,"] [","]@[",Replacer.ReplaceText,{"Столбец1"}),
    to = Table.ExpandListColumn(Table.TransformColumns(replace, {{"Столбец1", Splitter.SplitTextByDelimiter("@") }}), "Столбец1")
in
    to

Прикрепленные файлы

  • test_1.xlsx (20.55 КБ)

Соблюдение правил форума не освобождает от модераторского произвола
<#0>

 

Alex D

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

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

#3

11.10.2019 16:30:11

Цитата
buchlotnik написал:
вариант PQ:

Спасибо… может пригодится…
но немного не то…

 

Kuzmich

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

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

#4

11.10.2019 17:15:40

Цитата
макрос по переводу данных из строки в столбец
Код
Sub RowInColumn()
Dim mo As Object
Dim n As Integer
Dim i As Long
Dim iLastRow As Long
Dim iLR As Long
  Columns(2).ClearContents
  iLastRow = Cells(Rows.Count, 1).End(xlUp).Row
  Range("A1:A" & iLastRow).Copy Range("B1")
 With CreateObject("VBScript.RegExp")
   .Global = True
   .MultiLine = True
   .Pattern = "[[A-Za-z,s]+]"
   For i = 1 To iLastRow
     If .test(Cells(i, 1)) Then
       Set mo = .Execute(Cells(i, 1))
        If mo.Count > 1 Then
          Cells(i, 2) = mo(0)
           iLR = Cells(Rows.Count, 2).End(xlUp).Row
         For n = 1 To mo.Count - 1
           Cells(iLR + n, 2) = mo(n)
         Next
        End If
    End If
   Next
 End With
End Sub
 

Пытливый

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

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

#5

11.10.2019 17:31:29

Добрый день.
Можно попробовать таким макросом:

Скрытый текст

На копии листа — кнопка с побуждающей надписью.

Прикрепленные файлы

  • Копия test_1.xlsb (21.67 КБ)

Изменено: Пытливый11.10.2019 17:31:50

Кому решение нужно — тот пример и рисует.

 

Alex D

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

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

#6

12.10.2019 13:12:44

Цитата
Kuzmich написал:
макрос по переводу данных из строки в столбец

Спасибо. Все очнь хорошо рабтает. Однозначно в капилку приемов!

Цитата
Пытливый написал:
Можно попробовать таким макросом:

Спасибо. Как раз то что необходимо! Супер!

Всем хороших выходных!

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .‘s (eg .Range) they refer to the With statement object

Text to Columns feature can help you split text strings in Excel. Using VBA, you can make this process even faster. In this guide, we’re going to show you how to split text with VBA in Excel.

Download Workbook

Data

In this example, we have rows of data containing data separated by “|” characters. Each part represents an individual column.

Splitting text with VBA

If you are unfamiliar with VBA (Visual Basic for Applications), you can check out our beginner’s guide here: How to create a macro in Excel

Split Method

VBA has a function named Split which can return an array of sub-strings from a given string. The function parameters are the string to be split and a delimiter character which separates the sub-strings. In our example, the original strings are in cells in B6:B12 and there are “|” characters between the sub-strings.

The following code loops through each cell in the selected range, uses the Split function to create array of substrings, and uses another loop to distribute the sub-strings into adjacent cells in the same row.

Sub SplitText()
  Dim StringArray() As String, Cell As Range, i As Integer
  For Each Cell In Selection ‘To work on a static range replace Selection via Range object, e.g., Range(“B6:B12”)
    StringArray = Split(Cell, «|») ‘Change the delimiter with a character suits your data
    For i = 0 To UBound(StringArray)
      Cell.Offset(, i + 1) = StringArray(i)
      Cell.Offset(, i + 1).EntireColumn.AutoFit ‘This is for column width and optional.
    Next i
  Next
End Sub

You can copy paste the code above to use it in your workbook. However, make sure to update it depending on your data (i.e. change the delimiter or remove the Cell.Offset(, i + 1).EntireColumn.AutoFit if you do not want to change the column widths).

Text to Columns Method to split text with VBA

In VBA, you can call the Text to Columns feature of Excel. The method can be called for a range. Since we want to split cells by a delimiter, the argument DataType should be xlDelimited. The Destination argument determines the top-left cell for the split substrings. Each delimiter type has its own argument. Since the “|” character is not supported natively, our sample code sets Other as True and OtherChar as “|”.

Sub VBATextToColumns_Other()
  Dim MyRange As Range
  Set MyRange = Selection ‘To work on a static range replace Selection via Range object, e.g., Range(«B6:B12»)
  MyRange.TextToColumns Destination:=MyRange(1, 1).Offset(, 1), DataType:=xlDelimited, Other:=True, OtherChar:=»|»
End Sub

Text to Columns Method with multiple delimiters

Text to Columns method allows using multiple built-in delimiters at once. These are Tab, Semicolon, Comma and Space. Set any corresponding argument to True to enable the delimiter. The argument names are same with the character.

The following code can split the sample text by semicolon, comma, and space characters.

Sub VBATextToColumns_Multiple()
  Dim MyRange As Range
  Set MyRange = Selection ‘To work on a static range replace Selection via Range object, e.g., Range(«B6:B12»)
  MyRange.TextToColumns _
  Destination:=MyRange(1, 1).Offset(, 1), _
  TextQualifier:=xlTextQualifierDoubleQuote, _
  DataType:=xlDelimited, _
  SemiColon:=True, _
  Comma:=True, _
  Space:=True
End Sub

Содержание

  • Текст в столбцы

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

Текст в столбцы

В Диапазон.TextToColumns Метод в VBA — это мощный инструмент для очистки данных, которые были импортированы, например, из текстовых или CSV-файлов.

Рассмотрим следующий рабочий лист.

Данные поступили в Excel в одном столбце и разделены кавычками.

Вы можете использовать метод Range TextToColumns для разделения этих данных на столбцы.

Синтаксис TextToColumns

выражение.TextToColumns (Место назначения, Тип данных, TextQualifier, ПоследовательныйDelimiter, Вкладка, Точка с запятой, Запятая, Космос, Другой, Другое, FieldInfo, Десятичный разделитель, ТысячиСепаратор, TrailingMinusNumbers)

Выражение

Это диапазон ячеек, который вы хотите разделить, например: Диапазон («A1: A23»).

Все аргументы в методе TextToColumns являются необязательными (они заключены в квадратные скобки).

Место назначения

Куда вы хотите поместить результат — часто вы переопределяете данные и разделяете их в одном месте.

Тип данных

Тип используемого вами синтаксического анализа текста — это может быть xlDelimited (по умолчанию, если не указано), или xlFixedWidth.

TextQualifier

Если у вас есть кавычки (одинарные или двойные) вокруг каждого поля в тексте, который вы разделяете, вам необходимо указать, одинарные они или двойные.

ConsequtiveDelimiter

Это либо истина, либо ложь и указывает VBA рассматривать 2 одинаковых разделителя вместе, как если бы это был 1 разделитель.

Вкладка

Это либо Правда из Ложь, По умолчанию Ложь — это сообщает VBA, что данные разделены табуляцией.

Точка с запятой

Это либоПравда из Ложь, По умолчанию Ложь — это говорит VBA, что данные разделены точкой с запятой.

Космос

Это либо Правда из Ложь, По умолчанию Ложь — это сообщает VBA, что данные разделены пробелом.

Другой

Это либо Правда из Ложь, По умолчанию Ложь. Если вы установите это значение True, то следующий аргумент, Другое необходимо уточнить.

Другое

Это символ, которым разделяется текст (например: или |).

FieldInfo

Это массив, содержащий информацию о типе разделяемых данных. Первое значение в массиве указывает номер столбца в данных, а второе значение указывает константу, которую вы собираетесь использовать для отображения требуемого типа данных.

Примером для 5 столбцов с типами данных текст, числа и даты могут быть:

Массив (Массив (1, xlTextFormat), Массив (2, xlTextFormat), Массив (3, xlGeneralFormat), Массив (4, xlGeneralFormat), Массив (5, xlMDYFormat))

Другой способ установить это:

Массив (Массив (1, 2), Массив (2, 2), Массив (3, 1), Массив (4, 1), Массив (5, 3))

Числа во втором столбце — это значения констант, где константа xlTextFormat имеет значение 2, xlGeneralFormat (по умолчанию) имеет значение 1, а xlMDYFormat имеет значение 3.

Десятичный разделитель

Вы можете указать десятичный разделитель, который VBA должен использовать, если в данных есть числа. Если опущено, будет использоваться системная настройка, которая обычно представляет собой точку.

ТысячиСепаратор

Вы можете указать разделитель тысяч, который VBA должен использовать, если в данных есть числа. Если опущено, будет использоваться системная настройка, обычно это запятая.

TrailingMinusNumbers

Этот аргумент в основном предназначен для совместимости данных, которые генерируются из старых систем, где знак минус часто ставился после числа, а не перед ним. Вы должны установить это значение True, если отрицательные числа имеют знак минус позади них. По умолчанию — False.

Преобразование текста в столбцы

Следующая процедура преобразует данные Excel выше в столбцы.

12345678910111213141516 Sub TextToCol1 ()Диапазон («A1: A25»). TextToColumns _Назначение: = Диапазон («A1: A25»),Тип данных: = xlDelimited, _TextQualifier: = xlDoubleQuote, _ConsecutiveDelimiter: = True, _Tab: = False, _Точка с запятой: = False, _Запятая: = Ложь,Пробел: = True, _Другое: = Ложь, _FieldInfo: = Массив (Массив (1, 1), Массив (2, 1), Массив (3, 1), Массив (4, 1), Массив (5, 1)), _DecimalSeparator: = «.» , _ThousandsSeparator: = «,», _TrailingMinusNumbers: = TrueКонец подписки

В описанной выше процедуре мы заполнили все параметры. Однако для многих параметров установлено значение false или значение по умолчанию, и в этом нет необходимости. Более чистая версия вышеупомянутой процедуры изложена ниже. Вам необходимо использовать имена параметров, чтобы указать, какие параметры мы используем.

1234567 Sub TextToCol2 ()Диапазон («A1: A25»). TextToColumns _Тип данных: = xlDelimited, _TextQualifier: = xlDoubleQuote, _ConsecutiveDelimiter: = True, _Пробел: = True,Конец подписки

На самом деле требуется всего 4 параметра — данные разделяются двойными кавычками, вы хотите, чтобы последовательные кавычки обрабатывались как одна, а данные разделялись пробелом!

Для еще более быстрой строки кода мы могли бы опустить имена параметров, но тогда нам нужно будет поставить запятые, чтобы сохранить место параметра. Вам нужно ввести информацию только до последнего используемого параметра — в данном случае пробел, разделяющий данные, который является 8-м параметром.

123 Sub TextToCol3 ()Диапазон («A1: A25»). TextToColumns, xlDelimited, xlDoubleQuote, True,,,, TrueКонец подписки

После выполнения любой из описанных выше процедур данные будут разделены, как показано на рисунке ниже.

Понравилась статья? Поделить с друзьями:
  • Vba excel текст html
  • Vba excel таймер обратного отсчета
  • Vba excel таймер задержки
  • Vba excel таймер выполнения
  • Vba excel таблица умножения