Vba excel диапазон колонок

Свойства Column и Columns объекта Range в VBA Excel. Возвращение номера первого столбца и обращение к столбцам смежных и несмежных диапазонов.

Range.Column — свойство, которое возвращает номер первого столбца в указанном диапазоне.

Свойство Column объекта Range предназначено только для чтения, тип данных — Long.

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

Range(«B2:F10»).Select

MsgBox Selection.Column ‘Результат: 2

Range(«E1:F8,D4:G13,B2:F10»).Select

MsgBox Selection.Column ‘Результат: 5

Для возвращения номеров первых столбцов отдельных областей несмежного диапазона используется свойство Areas объекта Range:

Range(«E1:F8,D4:G13,B2:F10»).Select

MsgBox Selection.Areas(1).Column ‘Результат: 5

MsgBox Selection.Areas(2).Column ‘Результат: 4

MsgBox Selection.Areas(3).Column ‘Результат: 2

Свойство Range.Columns

Range.Columns — свойство, которое возвращает объект Range, представляющий коллекцию столбцов в указанном диапазоне.

Чтобы возвратить один столбец заданного диапазона, необходимо указать его порядковый номер (индекс) в скобках:

Set myRange = Range(«B4:D6»).Columns(1)  ‘Возвращается диапазон: $B$4:$B$6

Set myRange = Range(«B4:D6»).Columns(2)  ‘Возвращается диапазон: $C$4:$C$6

Set myRange = Range(«B4:D6»).Columns(3)  ‘Возвращается диапазон: $D$4:$D$6

Самое удивительное заключается в том, что выход индекса столбца за пределы указанного диапазона не приводит к ошибке, а возвращается диапазон, расположенный за пределами исходного диапазона (отсчет начинается с первого столбца заданного диапазона):

MsgBox Range(«B4:D6»).Columns(7).Address  ‘Результат: $H$4:$H$6

Если указанный объект Range является несмежным, состоящим из нескольких смежных диапазонов (областей), свойство Columns возвращает коллекцию столбцов первой области заданного диапазона. Для обращения к столбцам других областей указанного диапазона используется свойство Areas объекта Range:

Range(«E1:F8,D4:G13,B2:F10»).Select

MsgBox Selection.Areas(1).Columns(2).Address ‘Результат: $F$1:$F$8

MsgBox Selection.Areas(2).Columns(2).Address ‘Результат: $E$4:$E$13

MsgBox Selection.Areas(3).Columns(2).Address ‘Результат: $C$2:$C$10

Определение количества столбцов в диапазоне:

Dim c As Long

c = Range(«D5:J11»).Columns.Count

MsgBox c  ‘Результат: 7

Буква вместо номера

Если в качестве индекса столбца используется буква, она соответствует порядковому номеру этой буквы на рабочем листе:

  • "A" = 1;
  • "B" = 2;
  • "C" = 3;

и так далее.

Пример использования буквенного индекса вместо номера столбца в качестве аргумента свойства Columns объекта Range:

Range(«G2:K10»).Select

MsgBox Selection.Columns(2).Address ‘Результат: $H$2:$H$10

MsgBox Selection.Columns(«B»).Address ‘Результат: $H$2:$H$10

Обратите внимание, что свойство Range("G2:K10").Columns("B") возвращает диапазон $H$2:$H$10, а не $B$2:$B$10.


 

vikttur

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

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

Нужно скрывать определенное количество столбцов, задаваемое переменной. Начало блока известно — столбец J. Подскажите, как указать диапазон столбцов?  
       With Sheets(«list»)  
           .Columns(«J:IV»).Hidden = False  
           sttClmn = .Cells(1, 10).Column  
           finClmn = .Cells(1, i).Column  
…. Clmn=столбцы от sttClmn до finClmn  
           Clmn.Hidden = True  
       End With

 

R Dmitry

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

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

Excel,MSSQL,Oracle,Qlik

#2

30.09.2011 01:46:09

{quote}{login=vikttur}{date=30.09.2011 01:28}{thema=VBA динамический диапазон столбцов}{post}Нужно скрывать определенное количество столбцов, задаваемое переменной. Начало блока известно — столбец J. Подскажите, как указать диапазон столбцов?  
       With Sheets(«list»)  
           .Columns(«J:IV»).Hidden = False  
           sttClmn = .Cells(1, 10).Column  
           finClmn = .Cells(1, i).Column  
…. Clmn=столбцы от sttClmn до finClmn  
           Clmn.Hidden = True  
       End With{/post}{/quote}  
лучше так  
Range(Columns(1), Columns(3)).EntireColumn.Hidden = True

Спасибо

 

vikttur

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

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

 

KuklP

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

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

E-mail и реквизиты в профиле.

Точки забыл:  
           .Range(.Columns(10), .Columns(13)).EntireColumn.Hidden = True

Я сам — дурнее всякого примера! …

 

KuklP

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

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

E-mail и реквизиты в профиле.

Ну, или если хотца переменной:  
.Range(.Columns(10), .Columns(10+i)).EntireColumn.Hidden = True  
40014

Я сам — дурнее всякого примера! …

 

vikttur

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

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

Сам виноват. Спасибо, заработало. Ругается, если активен другой лист. Почему?  

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

 

vikttur

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

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

Оно! То есть они, точки. Спасибо за подсказку.

 

vikttur

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

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

Переменной хотца, конечно же, но это я сообразил :)  
Спасибо умам VBA от формулиста. Закрыли.

 

KuklP

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

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

E-mail и реквизиты в профиле.

Будешь должен формулу:-)Когда припечет.

Я сам — дурнее всякого примера! …

 

vikttur

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

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

Только если вместо простого решения полезешь, как я, в дебри :)

 

KuklP

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

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

E-mail и реквизиты в профиле.

Заметано.:-)

Я сам — дурнее всякого примера! …

 

ZVI

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

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

.EntireColumn — лишнее, потому что в данном случае диапазон итак определяется полными столбцами .Columns(…)  
Вот если бы ячейками, тогда — да.

 

vikttur

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

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

#13

01.10.2011 16:48:44

Спасибо. Буду знать.

Содержание

  1. Объект Range (Excel)
  2. Примечания
  3. Пример
  4. Методы
  5. Свойства
  6. См. также
  7. Поддержка и обратная связь
  8. Range.Columns property (Excel)
  9. Syntax
  10. Remarks
  11. Example
  12. Support and feedback
  13. Range object (Excel)
  14. Remarks
  15. Example
  16. Methods
  17. Properties
  18. See also
  19. Support and feedback

Объект Range (Excel)

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

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Примечания

Элемент по умолчанию объекта Range направляет вызовы без параметров в свойство Value, а вызовы с параметрами — в элемент Item. Таким образом, someRange = someOtherRange соответствует someRange.Value = someOtherRange.Value , someRange(1) соответствует someRange.Item(1) и someRange(1,1) соответствует someRange.Item(1,1) .

В разделе Пример описаны следующие свойства и методы для возврата объекта Range:

  • Свойства Range и Cells объекта Worksheet
  • Свойства Range и Cells объекта Range
  • Свойства Rows и Columns объекта Worksheet
  • Свойства Rows и Columns объекта Range
  • Свойство Offset объекта Range
  • Метод Union объекта Application

Пример

Чтобы вернуть объект Range, представляющий одну ячейку или диапазон ячеек, используйте синтаксис Range ( arg ), где arg обозначает диапазон. В следующем примере значение ячейки A1 помещается в ячейку A5.

В следующем примере диапазон A1:H8 заполняется случайными числами путем задания формулы для каждой ячейки в диапазоне. При использовании без квалификатора объекта (объекта слева от точки) свойство Range возвращает диапазон на активном листе. Если активное окно не является листом, метод завершается с ошибкой.

Используйте метод Activate объекта Worksheet, чтобы активировать лист перед использованием свойства Range без явного квалификатора объекта.

В следующем примере очищается содержимое диапазона Criteria.

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

Чтобы получить диапазон, содержащий все отдельные ячейки листа, используйте свойство Cells на листе. Вы можете обращаться к отдельным ячейкам, используя синтаксис Item(строка, столбец), где строка — индекс строки, а столбец — индекс столбца. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range. В следующем примере на первом листе активной книги ячейке A1 присваивается значение 24, а в ячейке B1 — значение 42.

В следующем примере задается формула для ячейки A2.

Хотя также можно использовать Range(«A1») , чтобы вернуть значение ячейки A1, иногда свойство Cells может быть удобнее, так как позволяет использовать переменную для строки или столбца. В следующем примере создаются заголовки столбцов и строк на листе Sheet1. Обратите внимание, что после активации листа можно использовать свойство Cells без явного объявления листа (оно возвращает ячейку на активном листе).

Хотя для изменения ссылок в стиле A1 можно использовать строковые функции Visual Basic, проще (и лучше при программировании) использовать нотацию Cells(1, 1) .

Используйте синтаксис_выражение_.Cells, где выражение возвращает объект Range, чтобы получить диапазон с тем же адресом, состоящий из отдельных ячеек. В таком диапазоне отдельные ячейки доступны с помощью синтаксиса Item(строка, столбец) относительно левого верхнего угла первой области диапазона. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range. В следующем примере на первом листе активной книги в ячейках C5 и D5 указывается формула.

Чтобы вернуть объект Range, используйте синтаксис Range ( ячейка1, ячейка2 ), где ячейка1 и ячейка2 — это объекты Range, указывающие начальную и конечную ячейки. В следующем примере устанавливается тип линии границы для ячеек A1:J10.

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

Чтобы получить диапазон, содержащий все строки листа, используйте свойство Rows на листе. Вы можете обращаться к отдельным строкам с помощью синтаксиса Item(строка), где строка — это индекс строки. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из строк. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются строки 5 и 10 первого листа активной книги.

Чтобы получить диапазон, содержащий все столбцы листа, используйте свойство Columns на листе. Вы можете обращаться к отдельным столбцам с помощью синтаксиса Item(строка) [sic], где строка — это индекс столбца в виде числа или адреса столбца в формате А1. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из столбцов. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются столбцы B, C, E и J первого листа активной книги.

Используйте синтаксис_выражение_.Rows, где выражение возвращает объект Range, чтобы получить диапазон, состоящий из строк первой области диапазона. Вы можете обращаться к отдельным строкам с помощью синтаксиса Item(строка), где строка — это относительный индекс строки от верхнего края первой области диапазона. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из строк. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются диапазоны C8:D8 и C6:D6 первого листа активной книги.

Используйте синтаксис_выражение_.Columns, где выражение возвращает объект Range, чтобы получить диапазон, состоящий из столбцов первой области диапазона. Вы можете обращаться к отдельным столбцам с помощью синтаксиса Item(строка) [sic], где строка — это относительный индекс столбца от левого края первой области диапазона, указанный в виде числа или адреса столбца в формате A1. Свойство Item можно пропустить, так как вызов направляется к нему с помощью элемента по умолчанию объекта Range.

Недопустимо указывать второй параметр свойства Item для диапазонов, состоящих из столбцов. Сначала нужно преобразовать их в отдельные ячейки, используя свойство Cells.

В следующем примере удаляются диапазоны L2:L10, G2:G10, F2:F10 и D2:D10 первого листа активной книги.

Чтобы вернуть диапазон с указанным смещением относительно другого диапазона, используйте синтаксис Offset ( строка, столбец ), где строка и столбец — это смещения строк и столбцов. В следующем примере выделяются ячейки, расположенные на три строки вниз и на один столбец вправо от ячейки в левом верхнем углу текущего выделенного фрагмента. Нельзя выбрать ячейку, которая находится не на активном листе, поэтому сначала необходимо активировать лист.

Используйте синтаксис Union ( диапазон1, диапазон2, . ) для возврата диапазонов из нескольких областей, то есть диапазонов, состоящих из двух или более смежных блоков ячеек. В следующем примере создается объект, определенный как объединение диапазонов A1:B2 и C3:D4, а затем выбирается определенный диапазон.

При работе с выделенными фрагментами, содержащими несколько областей, удобно применять свойство Areas. Оно разделяет выделенный фрагмент с несколькими областями на отдельные объекты Range, а затем возвращает объекты в виде коллекции. Используйте свойство Count в возвращенной коллекции, чтобы убедиться, что выделение содержит более одной области, как показано в следующем примере.

В этом примере используется метод AdvancedFilter объекта Range для создания списка уникальных значений, а также количества появлений этих уникальных значений в диапазоне столбца A.

Методы

Свойства

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Range.Columns property (Excel)

Returns a Range object that represents the columns in the specified range.

Syntax

expression.Columns

expression A variable that represents a Range object.

To return a single column, use the Item property or equivalently include an index in parentheses. For example, both Selection.Columns(1) and Selection.Columns.Item(1) return the first column of the selection.

When applied to a Range object that is a multiple-area selection, this property returns columns from only the first area of the range. For example, if the Range object has two areas—A1:B2 and C3:D4— Selection.Columns.Count returns 2, not 4. To use this property on a range that may contain a multiple-area selection, test Areas.Count to determine whether the range contains more than one area. If it does, loop over each area in the range.

The returned range might be outside the specified range. For example, Range(«A1:B2»).Columns(5).Select returns cells E1:E2.

If a letter is used as an index, it is equivalent to a number. For example, Range(«B1:C10»).Columns(«B»).Select returns cells C1:C10, not cells B1:B10. In the example, «B» is equivalent to 2.

Using the Columns property without an object qualifier is equivalent to using ActiveSheet.Columns . For more information, see the Worksheet.Columns property.

Example

This example sets the value of every cell in column one in the range named myRange to 0 (zero).

This example displays the number of columns in the selection on Sheet1. If more than one area is selected, the example loops through each area.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Range object (Excel)

Represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3D range.

Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

The default member of Range forwards calls without parameters to the Value property and calls with parameters to the Item member. Accordingly, someRange = someOtherRange is equivalent to someRange.Value = someOtherRange.Value , someRange(1) to someRange.Item(1) and someRange(1,1) to someRange.Item(1,1) .

The following properties and methods for returning a Range object are described in the Example section:

  • Range and Cells properties of the Worksheet object
  • Range and Cells properties of the Range object
  • Rows and Columns properties of the Worksheet object
  • Rows and Columns properties of the Range object
  • Offset property of the Range object
  • Union method of the Application object

Example

Use Range (arg), where arg names the range, to return a Range object that represents a single cell or a range of cells. The following example places the value of cell A1 in cell A5.

The following example fills the range A1:H8 with random numbers by setting the formula for each cell in the range. When it’s used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet. If the active sheet isn’t a worksheet, the method fails.

Use the Activate method of the Worksheet object to activate a worksheet before you use the Range property without an explicit object qualifier.

The following example clears the contents of the range named Criteria.

If you use a text argument for the range address, you must specify the address in A1-style notation (you cannot use R1C1-style notation).

Use Cells on a worksheet to obtain a range consisting all single cells on the worksheet. You can access single cells via Item(row, column), where row is the row index and column is the column index. Item can be omitted since the call is forwarded to it by the default member of Range. The following example sets the value of cell A1 to 24 and of cell B1 to 42 on the first sheet of the active workbook.

The following example sets the formula for cell A2.

Although you can also use Range(«A1») to return cell A1, there may be times when the Cells property is more convenient because you can use a variable for the row or column. The following example creates column and row headings on Sheet1. Be aware that after the worksheet has been activated, the Cells property can be used without an explicit sheet declaration (it returns a cell on the active sheet).

Although you could use Visual Basic string functions to alter A1-style references, it is easier (and better programming practice) to use the Cells(1, 1) notation.

Use_expression_.Cells, where expression is an expression that returns a Range object, to obtain a range with the same address consisting of single cells. On such a range, you access single cells via Item(row, column), where are relative to the upper-left corner of the first area of the range. Item can be omitted since the call is forwarded to it by the default member of Range. The following example sets the formula for cell C5 and D5 of the first sheet of the active workbook.

Use Range (cell1, cell2), where cell1 and cell2 are Range objects that specify the start and end cells, to return a Range object. The following example sets the border line style for cells A1:J10.

Be aware that the period in front of each occurrence of the Cells property is required if the result of the preceding With statement is to be applied to the Cells property. In this case, it indicates that the cells are on worksheet one (without the period, the Cells property would return cells on the active sheet).

Use Rows on a worksheet to obtain a range consisting all rows on the worksheet. You can access single rows via Item(row), where row is the row index. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.

The following example deletes row 5 and 10 of the first sheet of the active workbook.

Use Columns on a worksheet to obtain a range consisting all columns on the worksheet. You can access single columns via Item(row) [sic], where row is the column index given as a number or as an A1-style column address. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.

The following example deletes column «B», «C», «E», and «J» of the first sheet of the active workbook.

Use_expression_.Rows, where expression is an expression that returns a Range object, to obtain a range consisting of the rows in the first area of the range. You can access single rows via Item(row), where row is the relative row index from the top of the first area of the range. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of rows. You first have to convert it to single cells via Cells.

The following example deletes the ranges C8:D8 and C6:D6 of the first sheet of the active workbook.

Use_expression_.Columns, where expression is an expression that returns a Range object, to obtain a range consisting of the columns in the first area of the range. You can access single columns via Item(row) [sic], where row is the relative column index from the left of the first area of the range given as a number or as an A1-style column address. Item can be omitted since the call is forwarded to it by the default member of Range.

It’s not legal to provide the second parameter of Item for ranges consisting of columns. You first have to convert it to single cells via Cells.

The following example deletes the ranges L2:L10, G2:G10, F2:F10 and D2:D10 of the first sheet of the active workbook.

Use Offset (row, column), where row and column are the row and column offsets, to return a range at a specified offset to another range. The following example selects the cell three rows down from and one column to the right of the cell in the upper-left corner of the current selection. You cannot select a cell that is not on the active sheet, so you must first activate the worksheet.

Use Union (range1, range2, . ) to return multiple-area ranges—that is, ranges composed of two or more contiguous blocks of cells. The following example creates an object defined as the union of ranges A1:B2 and C3:D4, and then selects the defined range.

If you work with selections that contain more than one area, the Areas property is useful. It divides a multiple-area selection into individual Range objects and then returns the objects as a collection. Use the Count property on the returned collection to verify a selection that contains more than one area, as shown in the following example.

This example uses the AdvancedFilter method of the Range object to create a list of the unique values, and the number of times those unique values occur, in the range of column A.

Methods

Properties

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Excel VBA Columns Property

VBA Columns property is used to refer to columns in the worksheet. Using this property we can use any column in the specified worksheet and work with it.

When we want to refer to the cell, we use either the Range object or Cells property. Similarly, how do you refer to columns in VBA? We can refer to columns by using the “Columns” property. Look at the syntax of COLUMNS property.

Table of contents
  • Excel VBA Columns Property
    • Examples
      • Example #1
      • Example #2 – Select Column Based on Variable Value
      • Example #3 – Select Column Based on Cell Value
      • Example #4 – Combination of Range & Column Property
      • Example #5 – Select Multiple Columns with Range Object
    • Recommended Articles

Columns Property

We need to mention the column number or header alphabet to reference the column.

For example, if we want to refer to the second column, we can write the code in three ways.

Columns (2)

Columns(“B:B”)

Range (“B:B”)

Examples

You can download this VBA Columns Excel Template here – VBA Columns Excel Template

Example #1

If you want to select the second column in the worksheet, then first, we need to mention the column number we need to select.

Code:

Sub Columns_Example()

  Columns (2)

End Sub

Now, put a dot (.) to choose the “Select” method.

One of the problems with this property is we do not get to see the IntelliSense list of VBA.

Code:

Sub Columns_Example()

  Columns(2).Select

End Sub

So, the above VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more will select the second column of the worksheet.

VBA Columns Example

Instead of mentioning the column number, we can use the column header alphabet “B” to select the second column.

Code:

Sub Columns_Example()

  Columns("B").Select
  Columns("B:B").Select

End Sub

The above codes will select column B, i.e., the second column.

Example #2 – Select Column Based on Variable Value

We can also use the variable to select the column number. For example, look at the below code now.

Code:

Sub Columns_Example()

  Dim ColNum As Integer
  ColNum = 4
  Columns(ColNum).Select

End Sub

In the above, we have declared the variable as “Integer” and assigned the value of 4 to this variable.

We have supplied this variable instead of the column number for the Column’s property. Since the variable holds the value of 4, it will select the 4th column.

Example #3 – Select Column Based on Cell Value

We have seen how to select the column based on variable value now. Next, we will see how we can select the column based on the cell value number. For example, in cell A1 we have entered the number 3.

VBA Columns Example 1

The code below will select the column based on the number in cell A1.

Code:

Sub Columns_Example()

  Dim ColNum As Integer
  ColNum = Range("A1").Value
  Columns(ColNum).Select

End Sub

The above code is the same as the previous one. Still, the only thing we have changed here is instead of assigning the direct number to the variable. Instead, we gave a variable value as “whatever the number is in cell A1.”

Since we have a value of 3 in cell A1, it will select the third column.

Example #4 – Combination of Range & Column Property

We can also use the Columns property with the Range object. Using the Range object, we can specify the specific range. For example, look at the below code.

Code:

Sub Columns_Example1()

  Range("C1:D5").Columns(2).Select

End Sub

In the above example, we have specified the range of cells as C1 to D5. Then, using the columns property, we have specified the column number as 2 to select.

Now, in general, our second column is B. So the code has to select the “B” column but see what happens when we run the code.

Example 2

It has selected the cells from D1 to D5.

In our perception, it should have selected the second column, i.e., column B. But now, it has selected the cells from D1 to D5.

It has selected these cells because before using the COLUMNS property, we have specified the range using the RANGE object as C1 to D5. Now, the property thinks within this range as the columns and selects the second column in the range C1 to D5. Therefore, D is the second column, and specified cells are D1 to D5.

Example #5 – Select Multiple Columns with Range Object

Using the Range object and Columns property, we can select multiple columns. For example, look at the below code.

Code:

Sub Columns_Example1()

  Range(Columns(2), Columns(5)).Select

End Sub

The code will select the column from the second column to the fifth column, i.e., from column B to E.

Example 3

We can also write the code in this way.

Code:

Sub Columns_Example1()

  Range(Columns(B), Columns(E)).Select

End Sub

The above is the same as the previous one and selects the columns from B to E.

Like this, we can use the COLUMNS property to work with the worksheet.

Recommended Articles

This article has been a guide to VBA Columns. Here, we discuss examples of the column property in Excel VBA and select multiple columns with the range object and downloadable Excel templates. Below are some useful articles related to VBA: –

  • DateSerial Function in Excel VBA
  • Hide Columns in VBA
  • Insert Columns in VBA
  • Delete Column in VBA
  • VBA Variable Types

I would like to select multiple columns.

Eg. I want to select column a, b, d, e, g, h

I’ve tried:

Columns("A, B, D, E, G, H").select

I get error message: Type mismatch.

Community's user avatar

asked Jan 17, 2012 at 0:49

HL8's user avatar

2

Range("A:B,D:E,G:H").Select can help

Edit note: I just saw you have used different column sequence, I have updated my answer

answered Jan 17, 2012 at 0:53

HRgiger's user avatar

HRgigerHRgiger

2,72026 silver badges37 bronze badges

2

Some things of top of my head.

Method 1.

Application.Union(Range("a1"), Range("b1"), Range("d1"), Range("e1"), Range("g1"), Range("h1")).EntireColumn.Select

Method 2.

Range("a1,b1,d1,e1,g1,h1").EntireColumn.Select

Method 3.

Application.Union(Columns("a"), Columns("b"), Columns("d"), Columns("e"), Columns("g"), Columns("h")).Select

answered Jan 17, 2012 at 1:03

GSerg's user avatar

GSergGSerg

75.3k17 gold badges160 silver badges340 bronze badges

1

Some of the code looks a bit complex to me. This is very simple code to select only the used rows in two discontiguous columns D and H. It presumes the columns are of unequal length and thus more flexible vs if the columns were of equal length.

As you most likely surmised 4=column D and 8=column H

Dim dlastRow As Long
Dim hlastRow As Long

dlastRow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
hlastRow = ActiveSheet.Cells(Rows.Count, 8).End(xlUp).Row
Range("D2:D" & dlastRow & ",H2:H" & hlastRow).Select

Hope you find useful — DON’T FORGET THAT COMMA BEFORE THE SECOND COLUMN, AS I DID, OR IT WILL BOMB!!

Jose Ricardo Bustos M.'s user avatar

answered Dec 4, 2016 at 15:33

MORTON WAKELAND JR's user avatar

Working on a project I was stuck for some time on this concept — I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I’m working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn’t include the entire code because at this point it’s fairly long — if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable «SelectRanges» as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

answered Jan 7, 2016 at 3:18

Jonh's user avatar

JonhJonh

11113 bronze badges

As a recorded macro.

range("A:A, B:B, D:D, E:E, G:G, H:H").select

answered Mar 8, 2018 at 15:56

gavin's user avatar

gavingavin

3051 gold badge2 silver badges12 bronze badges

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