Текст по столбцам excel vba

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!

Use the TextToColumns method of the Range object.

expression.TextToColumns(Destination, DataType,TextQualifier, ConsecutiveDelimiter, Tab, _
Semicolon, Comma, Space, Other,OtherChar, FieldInfo, DecimalSeparator, _
ThousandsSeparator,TrailingMinusNumbers)

The code below relates to the data shown above. To perform a simple text to columns procedure you only need to use the Destination & DataType parameters and then specify the delimiter eg Space:= True. DataType defaults to delimited rather than fixed width, so strictly not needed in the code below.

Range("B1")= "First Name"
Range("C1")= "Last Name"
Range("A2",Range("A2").End(xlDown)).TextToColumns _
Destination:=Range("B2"), DataType:=xlDelimited,Space:=True
Columns("B:C").AutoFit
Range("A1",Range("A1").End(xlDown)).Copy
Range("B1",Range("B1").End(xlToRight).End(xlDown)).PasteSpecial _
Paste:=xlPasteFormats
Application.CutCopyMode= False

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

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

 

Добрый день, помогите со скриптом который бы разбивал текст по колонкам через разделитель «-» ,
Пример колонки «A» 4029038-93 разбивал на колонка «A»  4029038 и колонка «B» 93

 

vikttur

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

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

Закладка Данные-Текст по столбцам.
Если этого мало, прикрепите к первому сообщению небольшой пример.

 

Алексей Коваленко

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

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

#3

24.05.2021 14:48:52

vikttur, Воспользовался записью макроса, мне именно макрос нужен был для этого действия

Код
Sub Макрос1()
    Columns("A").Select
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
        :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
End Sub

Подскажите как применить данную функцию к другому листу ?

 

Mershik

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

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

#4

24.05.2021 15:08:00

Цитата
Алексей Коваленко написал:
Подскажите как применить данную функцию к другому листу ?

выделяете данные на другом листе, но думаю у Вас иной вопрос — наверное как вывести результат на другой лист, поэтому советую показать файл-пример с исходными данными и желаемым результатом

Изменено: Mershik24.05.2021 15:08:59

Не бойтесь совершенства. Вам его не достичь.

 

Mershik, У меня «Литс1» активный на котором я нахожусь и у меня несколько макросов запускаются с активного листа , но мне нужно разделить ячейку на столбцы  с Лист2. У меня на Лист2 есть колонка «A» в которой есть текс который нужно разделить через разделитель «-» на колонку «B» у меня это работает когда у меня активный лист «Лист2»  

 

Алексей Коваленко

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

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

#6

24.05.2021 15:24:21

Цитата
Mershik написал:
Вас иной вопрос — наверное как вывести результат на другой лист,

Да , у меня к примеру Лист1 пустой и я нахожусь на нем , а мне нужно чтобы выполнение данной операции происходило на листе  «Лист2»
Мне нужно выполнить данный скрипт только с листа «Лист1»,

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

  • Пример.xlsx (9.99 КБ)

Изменено: Алексей Коваленко24.05.2021 15:28:49

 

vikttur

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

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

Алексей Коваленко, свои сообщения можно дополнять

 

МатросНаЗебре

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

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

#8

24.05.2021 15:29:26

Код
Sub Макрос1()
    Sheets("Лист2").Columns("A").TextToColumns Destination:=Sheets("Лист2").Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
        :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
End Sub

 

МатросНаЗебре, Спасибо, я пробовал добавлять только Sheets(«Лист2»).Columns(«A»), а Sheets(«Лист2»).Range(«A1») не додумался добавить .

 

Mershik

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

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

#10

24.05.2021 15:31:18

Алексей Коваленко,

Код
Sub mrshkei()
Dim arr, arr2, arr3, i As Long, lr As Long
Dim sh As Worksheet, sh2 As Worksheet
Set sh = Worksheets("Лист1"): Set sh2 = Worksheets("Лист2")
arr = sh2.Range("A1:A" & sh2.Cells(Rows.Count, 1).End(xlUp).Row)
ReDim arr3(1 To UBound(arr), 1 To 2)
For i = LBound(arr) To UBound(arr)
    arr2 = Split(arr(i, 1), "-")
    For n = LBound(arr2) To UBound(arr2)
        arr3(i, n + 1) = arr2(n)
    Next n
Next i
sh.Range("A1").Resize(UBound(arr3), 2) = arr3
End Sub

Не бойтесь совершенства. Вам его не достичь.

Студворк — интернет-сервис помощи студентам

Всем привет! Это моя первая тема. Пытался сделать сам, но спустя 4 дня, терпение кончилось. И без вашей помощи мне уже не справиться. Я снимаю отчет несоклько раз в день. Постоянно приходиться столбцы удалять, вставлять, копировать и т.д, чтобы вытянуть нужные для меня данные. Делать одни и теже манипуляции уже надоело. Я пытаюсь хоть как-то автоматизировать процесс, но ничего не выходит. С макросами у меня совсем беда. Пытался это сделать через запись макроса, но постоянно, что-то выходит не так.

Так вот, суть в следующем, есть отчет, из него мне необходмо вытянуть определнные данные, чтобы эти данные уже вставить в другой отчет.
В файлике, красным цветом выделены столбцы, которые необходимо разделить по столбцам и затем их совместить. Желтым выделены столбцы, которые необходимо оставить. Итоговая таблицы, которая должна получиться, указана во второй вкладке. Т.е. все данные , которые мы разелили по столбцам, совместили С и D.

Буду очень признателен за любую помощь.

Понравилась статья? Поделить с друзьями:
  • Текст подсказка в word
  • Текст по столбцам excel 2016
  • Текст подсказка в excel
  • Текст по столбцам excel 2007
  • Текст под углом в word