Excel макросы текст по столбцам

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

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

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

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

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

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!

Текст по столбцам и строкам

Подробности
Создано 03 Май 2012

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

В примере созданы 2 сложные формулы для разбивки текста по столбцам и строкам. Их также можно использовать для выборки текстовой составляющей по порядковому номеру.

Напомним, что интерфейсное средство «Текст по столбцам» доступно через меню и ленту Excel Данные Текст по столбцам.

В файле-примере показано два типа формулы для разделения текста на составляющие:

  • текст по столбцам (диапазон B5:K6)
  • текст по строкам (диапазон A10:B19)

В качестве разделителя текста используется символ «,»  (запятая). В служебных целях задействованы еще два символа «<» и «>» (математические знаки «меньше» и «больше»). Эти символы не могут находится в исходном тексте, в противном случае формула будет работать неверно. И разделитель, и служебные символы можно заменить на любые другие, главное, чтобы они не могли быть задействованы в исходном тексте. Для замены исправьте константы во всех местах формулы.

Формула в ячейке B5 и далее по столбцам обрабатывает исходный текст из ячейки A5:

 
=TRIM(IF(ISERR(FIND(">";SUBSTITUTE(SUBSTITUTE(","&$A5&",";",";"<";COLUMNS($B:B));",";">";COLUMNS($B:B))));"";
    MID(SUBSTITUTE(SUBSTITUTE(","&$A5&",";",";"<";COLUMNS($B:B));",";">";COLUMNS($B:B));
      FIND("<";SUBSTITUTE(SUBSTITUTE(","&$A5&",";",";"<";COLUMNS($B:B));",";">";COLUMNS($B:B)))+1;
      FIND(">";SUBSTITUTE(SUBSTITUTE(","&$A5&",";",";"<";COLUMNS($B:B));",";">";COLUMNS($B:B)))-FIND("<";SUBSTITUTE(SUBSTITUTE(","&$A5&",";",";"<";COLUMNS($B:B));",";">";COLUMNS($B:B)))-1)))

Формула в ячейке A10 и далее по строкам обрабатывает исходный текст из ячейки A9:

 
=TRIM(IF(ISERR(FIND(">";SUBSTITUTE(SUBSTITUTE(","&A$9&",";",";"<";ROWS($10:10));",";">";ROWS($10:10))));"";
    MID(SUBSTITUTE(SUBSTITUTE(","&A$9&",";",";"<";ROWS($10:10));",";">";ROWS($10:10));
      FIND("<";SUBSTITUTE(SUBSTITUTE(","&A$9&",";",";"<";ROWS($10:10));",";">";ROWS($10:10)))+1;
      FIND(">";SUBSTITUTE(SUBSTITUTE(","&A$9&",";",";"<";ROWS($10:10));",";">";ROWS($10:10)))-FIND("<";SUBSTITUTE(SUBSTITUTE(","&A$9&",";",";"<";ROWS($10:10));",";">";ROWS($10:10)))-1)))

Формулы ссылаются только на исходный текст и не требуют наличия других предварительно вычисленных составляющих. Варианты отличаются только автоматическим определением порядкового номера текстовой составляющей, в первом случае — это подформула для вычисления номера от количества столбцов: COLUMNS($B:B); во втором — от количества строк: ROWS($10:10). При копировании диапазон столбцов и строк автоматически расширяется, вычисляя таким образом нужное значение. Вместо этой подформулы можно задать константу или переменную, определяющую требуемый номер. Из результатирующих текстовых значений убираются лишние пробелы при помощи функции TRIM().

Наверняка можно сделать формулу покороче, используя другие методы поиска. Это просто наш вариант — оригинальный, нигде не подсмотренный ;)

Смотри также

» Извлечение чисел из набора строк

Небольшой пример по использованию операции замены текста, который часто встречается на практике. Требуется вырезать из набора…

» Объединение строк

У продвинутых пользователей Excel очень популярен вопрос о возможности объединения диапазона ячеек, содержащих текст, в одну строку при…

» Объединение строк

Функция efSumText возвращает объединенный текст с указанным разделителем.

Понравилась статья? Поделить с друзьями:
  • Excel макросы текст в число
  • Excel макросы для экономиста
  • Excel макросы сумма ячеек
  • Excel макросы для учета
  • Excel макросы ссылки с файла на файл