Excel vba columns несколько столбцов

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

Содержание

  1. Range.Columns property (Excel)
  2. Syntax
  3. Remarks
  4. Example
  5. Support and feedback
  6. См. раздел «Строки и столбцы»
  7. Об участнике
  8. Поддержка и обратная связь
  9. Свойство Range.Columns (Excel)
  10. Синтаксис
  11. Замечания
  12. Пример
  13. Поддержка и обратная связь
  14. VBA Columns
  15. Excel VBA Columns Property
  16. Examples
  17. Example #1
  18. Example #2 – Select Column Based on Variable Value
  19. Example #3 – Select Column Based on Cell Value
  20. Example #4 – Combination of Range & Column Property
  21. Example #5 – Select Multiple Columns with Range Object
  22. Recommended Articles
  23. Using the Excel Range Columns property in VBA
  24. Set Columns as Range
  25. N-th item in the collection
  26. Counting columns and cells
  27. Column in range and EntireColumn
  28. Select one or more columns in the columns collection using column character
  29. Loop over columns in Range

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.

Источник

См. раздел «Строки и столбцы»

Используйте свойство Rows или Columns для работы с целыми строками или столбцами. Эти свойства возвращают объект Range , представляющий диапазон ячеек. В следующем примере Rows(1) возвращает строку 1 на листе Sheet1. Затем для свойства Bold объекта Font для диапазона задается значение True.

В следующей таблице показаны некоторые ссылки на строки и столбцы с помощью свойств Rows и Columns .

Reference Смысл
Rows(1) Строка 1
Rows Все строки на листе
Columns(1) Столбец 1
Columns(«A») Столбец 1
Columns Все столбцы на листе

Чтобы одновременно работать с несколькими строками или столбцами, создайте переменную объекта и используйте метод Union , объединяя несколько вызовов свойства Rows или Columns . В следующем примере формат строк один, три и пять на листе один в активной книге изменяется полужирным шрифтом.

Пример кода, предоставляемый: Деннис Валлентин( Dennis Wallentin), VSTO & .NET & Excel В этом примере удаляются пустые строки из выбранного диапазона.

В этом примере удаляются пустые столбцы из выбранного диапазона.

Об участнике

Деннис Валлентин является автором блога VSTO & .NET & Excel, в который основное внимание уделяется решениям платформа .NET Framework для Excel и службы Excel. Деннис разрабатывает решения Excel более 20 лет и также является соавтором книги «Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft Excel, VBA, and .NET (2nd Edition)».

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

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

Источник

Свойство Range.Columns (Excel)

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

Синтаксис

expression. Столбцы

выражение: переменная, представляющая объект Range.

Замечания

Чтобы вернуть один столбец, используйте свойство Item или аналогично включите индекс в круглые скобки. Например, и Selection.Columns(1) возвращают Selection.Columns.Item(1) первый столбец выделенного фрагмента.

При применении к объекту Range , который является выделенным с несколькими областями, это свойство возвращает столбцы только из первой области диапазона. Например, если объект Range имеет две области — A1:B2 и C3:D4, возвращает Selection.Columns.Count значение 2, а не 4. Чтобы использовать это свойство в диапазоне, который может содержать выбор из нескольких областей, проверьте Areas.Count , содержит ли диапазон несколько областей. Если это так, выполните цикл по каждой области в диапазоне.

Возвращаемый диапазон может находиться за пределами указанного диапазона. Например, Range(«A1:B2»).Columns(5).Select возвращает ячейки E1:E2.

Если буква используется в качестве индекса, она эквивалентна числу. Например, Range(«B1:C10»).Columns(«B»).Select возвращает ячейки C1:C10, а не ячейки B1:B10. В примере «B» эквивалентно 2.

Использование свойства Columns без квалификатора объекта эквивалентно использованию ActiveSheet.Columns . Дополнительные сведения см. в свойстве Worksheet.Columns .

Пример

В этом примере для каждой ячейки в столбце один в диапазоне с именем myRange задается значение 0 (ноль).

В этом примере отображается количество столбцов в выделенном фрагменте на листе Sheet1. Если выбрано несколько областей, в примере выполняется цикл по каждой области.

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

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

Источник

VBA Columns

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

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.

Examples

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:

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:

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

Code:

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:

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.

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

Code:

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:

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.

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:

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

We can also write the code in this way.

Code:

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: –

Источник

Using the Excel Range Columns property in VBA

The following sections explain how you can use worksheet or range object .Columns property. It begins with explaining several ways to select a column. At the end, I will explain how to loop over the columns collection.

Set Columns as Range

The .Columns property returns a range as a collection of columns, the selected range of columns. Which columns are included is determined by the RowIndex and ColumnIndex properties as explained below. There are three classes that support the Columns property:

  • Application.Columns : All columns on the active worksheet. This is what is assumed when Columns is called without specifying the range or worksheet.
  • Worksheets(«Sheet1»).Columns(«B:D») : columns B, C and D on the specified worksheet.
  • Range(«B2:D3»).Columns(2) : The second columns in the specified range, here C.

There are two ways to identify column(s) in the Columns collection:

  1. N-th item in the columns collection
  2. Select column in the columns collection using column character

Another ways to identify a column is using the range address, e.g. Range(«B:B») , or Range(«B:D») for columns B, C and D.

N-th item in the collection

When leaving out the second optional argument ColumnIndex , the Columns property returns the nth item. The order in which items get returned is breadth-first, so in the example table the columns with value a,b,c. f.

Expression Value Comment
Range(«B2:C3»).Columns(2) C The second column in the range
Range(«B2:C3»).Columns(3) D Even though the range only has two columns, .
Note
Negative values in the index are not allowed.

Counting columns and cells

Range(«B2:C3»).Columns.Count returns 2 columns, Range(«B2:C3»).Columns.Cells.Count returns 4 cells.

Column in range and EntireColumn

As shown in above example, Columns applied to a range only includes the cells in that range. To get the complete column, apply EntireColumn .

Select one or more columns in the columns collection using column character

Expression Column Comment
Range(«B2:B3»).Columns(«B») C Column character interpreted as number, e.g. «B» is always 2nd column, even if not in the original range
Range(«B2:B3»).Columns(«B:C») C and D Column character interpreted as number, e.g. «B» is always 2nd column

Loop over columns in Range

The Columns property is particularly useful because it makes it easy to iterate over a range. The image below shows the part of the Code VBA (download) menu that lets you insert the code fragment you require.

Источник

Свойства 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.


 

Мартын

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

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

#1

22.12.2016 11:32:51

Здравствуйте, все!
Вопрос такой: есть на листе таблица «Table1», в VBA ей соответствует ListObjects(«Table1»).
В таблице есть несколько столбцов с именами «a», «b», «c».
Мне надо выбрать (для копирования) области данных нескольких смежных столбцов одновременно. Как это сделать???
Данные (без заголовка!) одного столбца выбираются элементарно:

Код
Dim r As Range
Set r=ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1").ListColumns.Item("b").DataBodyRange
r.Copy

и т.д…..
А вот как выбрать данные сразу двух/трёх/ и т.д. столбцов этой «умной таблицы»???

 

Пытливый

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

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

#2

22.12.2016 11:37:37

Сделал на листочке простую «умную» таблицу с заголовками «Один», «Два», «Три»
Забил 3-4 строк данных
Включил макрорекордер
Выделил столбец «ОДИН», «ДВА»
Получил код:

Код
 Range("Таблица1[[#All],[Один]:[Два]]").Select

Может через это как-то попробовать?

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

 

Sanja

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

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

#3

22.12.2016 13:10:29

Ничего лучшего не придумал  :(. Union

Код
Dim r As Range
With Worksheets("Лист1").ListObjects("Таблица1")
    Set r = Union(.ListColumns("b").DataBodyRange, .ListColumns("c").DataBodyRange)
End With
r.Copy

Изменено: Sanja22.12.2016 13:10:48

Согласие есть продукт при полном непротивлении сторон.

 

Мартын

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

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

#4

22.12.2016 14:00:21

Цитата
Sanja написал: Union

Может быть и прокатит, но хочется верить, что создатели  VBA догадывались, что кому-нибудь может потребоваться выбрать более одного столбца и предусмотрели некий простой и удобный вариант. Только забыли его задокументировать. :(

 

Dima S

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

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

#5

22.12.2016 22:19:52

Цитата
Range(«Таблица1[[#All],[Один]:[Два]]»).Select

чем не

Цитата
простой и удобный вариант

Изменено: Dima S22.12.2016 22:20:25

 

Sanja

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

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

#7

22.12.2016 23:25:35

Цитата
Мартын написал: области данных нескольких смежных столбцов одновременно
Код
Set r = Worksheets("Лист1").ListObjects("Таблица1").DataBodyRange.Columns("b:c")

Согласие есть продукт при полном непротивлении сторон.

 

Мартын

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

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

Sanja, огромное спасибо!!! Я верил, что простой способ есть!

 

Sanja

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

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

:D Просто попробовал расставить свойства объекта ListObjects(«Таблица1») в той последовательности, которая требовалась

Согласие есть продукт при полном непротивлении сторон.

 

RAN

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

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

#10

23.12.2016 18:45:57

Цитата
Мартын написал:
Я верил, что простой способ есть!

Но не этот  :)

Код
Set r = Worksheets("Лист1").ListObjects("Таблица1").ListColumns("b").DataBodyRange

и

Код
Set r = Worksheets("Лист1").ListObjects("Таблица1").DataBodyRange.Columns("b")

дадут два совершенно различных диапазона (если только случайно второй столбец таблицы не имеет имя «b»)

Код
Sub qq()
    With Worksheets("Лист1").ListObjects("Таблица1")
        Set r = .DataBodyRange.Offset(, .ListColumns("b").Index - 1) _
                .Resize(, .ListColumns("d").Index - .ListColumns("b").Index + 1)
    End With
    r.Select
End Sub
 

Sanja

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

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

#11

24.12.2016 08:39:50

RAN, точно, промашка вышла. Названия столбцов действительно совпадали с их заголовками (#7)
Не понял для чего .Offset

Код
Sub ListO()
Dim r As Range
With Worksheets("Лист1").ListObjects("Таблица1")
'   Если известна величина смещения
'    Set r = .ListColumns("Clm2").DataBodyRange.Resize(, 3)
'   По названию столбца
    Set r = .ListColumns("Clm2").DataBodyRange. _
        Resize(, .ListColumns("Clm4").Index - .ListColumns("Clm2").Index + 1)
End With
    r.Select
'    r.Copy
End Sub

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

  • Выбор смежных столбцов в умной таблице.xlsm (14.96 КБ)

Изменено: Sanja24.12.2016 09:43:00

Согласие есть продукт при полном непротивлении сторон.

 

RAN

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

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

#12

24.12.2016 10:12:00

Цитата
Sanja написал: Не понял для чего .Offset

Перемудрил

 

ZVI

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

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

#13

25.12.2016 01:02:08

Для

примера

таблицы Андрея из сообщения

#11

Код
' Выделить смежные столбцы DataBodyRange со 2-го по 4-й
Sub Столбцы234()
  Range("Таблица1[[Clm2]:[Clm4]]").Select
  ' или так:
  'Range("Таблица1[Clm2]").Resize(,3).Select
End Sub

' Выделить несмежные столбцы DataBodyRange 2-й и 4-й
Sub Столбцы24()
  Range("Таблица1[Clm2],Таблица1[Clm4]").Select
End Sub

Изменено: ZVI25.12.2016 04:48:28

 

Мартын

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

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

Нашел простой ИМХО способ:
Dim r As Range
With ThisWorkbook.Worksheets(«Sheet1»).ListObjects(«Table1»)
Set r = Range(.ListColumns(«clm2»).DataBodyRange, .ListColumns(«clm4»).DataBodyRange)
r.copy
end with

 

tchack

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

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

#15

19.12.2022 17:47:26

Цитата
Пытливый написал:
Сделал на листочке простую «умную» таблицу с заголовками «Один», «Два», «Три»Забил 3-4 строк данныхВключил макрорекордерВыделил столбец «ОДИН», «ДВА»Получил код:Код ? 1Range(«Таблица1[[#All],[Один]:[Два]]»).SelectМожет через это как-то попробовать?

А как таким образом выделить столбец «Один», «Пять», «Восемь»??

 

нажмите Ctrl

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

tchack

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

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

#17

19.12.2022 18:11:41

Цитата
Ігор Гончаренко написал:
нажмите Ctrl

Таким способом:

Код
Range("Таблица1[[#All],[Один]:[Два]]").Select

При выборе несмежных столбцов макрорекордер пишет обычный диапазон (не диапазон умной таблицы).

 

Дмитрий(The_Prist) Щербаков

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

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

Профессиональная разработка приложений для MS Office

#18

19.12.2022 18:19:39

Цитата
написал:
При выборе несмежных столбцов

выше же дали способ — чем не подходит? Сообщение

#13

от 25.12.2016 01:02:08

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

tchack

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

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

#19

19.12.2022 19:09:34

Цитата
Дмитрий(The_Prist) Щербаков написал:
выше же дали способ — чем не подходит?

Столбцы «Один» и «Два» смежные:

Код
Range("Таблица1[[#All],[Один]:[Два]]").Select

Столбцы «Один», «Пять», «Восемь» — несмежные, а перечисление через запятую выдает ошибку:

Код
Range("Таблица1[[#All],[Один],[Пять],[Восемь]]").Select
 

sokol92

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

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

#20

19.12.2022 20:32:32

Найдите разницу между #13:

Код
Range("Таблица1[Clm2],Таблица1[Clm4]")

и #19:

Код
Range("Таблица1[[#All],[Один],[Пять],[Восемь]]")

Владимир

 

tchack

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

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

sokol92, благодарю. Не обратил внимание.

 

tchack

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

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

#22

19.12.2022 22:05:33

Возможно ли соединить два таких диапазона в одном объекте Range:

Код
Sheet1.Range( _
"Таблица1[ОДИН]," + _
"Таблица1[ПЯТЬ]," + _
"Таблица1[ВОСЕМЬ]").Select
Код
Sheet1.Range("Таблица1").Columns(10).Select

Изменено: tchack19.12.2022 22:05:56

 

New

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

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

#23

19.12.2022 23:40:48

Код
Sub Test()
    Dim Sheet1 As Worksheet
    
    Set Sheet1 = ActiveSheet
    
    Sheet1.Range("Таблица1[Column2]").Select
    Sheet1.Range("Таблица1[Column1],Таблица1[Column5],Таблица1[Column8]").Select
    Sheet1.Range("Таблица1").Columns(10).Select
    
    Dim Rng1 As Range
    Dim Rng2 As Range
    Dim Rng3 As Range
    
    Set Rng1 = Sheet1.Range("Таблица1[Column1],Таблица1[Column5],Таблица1[Column8]")
    Set Rng2 = Sheet1.Range("Таблица1").Columns(10)
    
    Set Rng3 = Union(Rng1, Rng2)
    Rng3.Select
    
End Sub
 

tchack

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

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

#24

19.12.2022 23:55:35

New, спасибо, так лучше:

Код
    Application.Union(Sheet1.Range( _
       "Таблица1[ОДИН]," + _
       "Таблица1[ПЯТЬ]," + _
       "Таблица1[ВОСЕМЬ]" _
    ), Sheet1.Range("Таблица1").Columns(10)).Select

но я ищу вариант без Union (если это возможно).

Изменено: tchack19.12.2022 23:56:01

 

New

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

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

если честно, вы ищите костыли )

 

Дмитрий(The_Prist) Щербаков

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

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

Профессиональная разработка приложений для MS Office

#26

20.12.2022 08:29:43

Цитата
написал:
я ищу вариант без Union

Вы бы еще написали зачем эти грабли вообще Вам нужны — может чего и придумалось бы. А пока выглядит как желание капризного ребенка — хочу и все :)
Без обид, но никто не понимает почему нельзя Union и почему не подходят другие предложенные варианты.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

tchack

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

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

Дмитрий(The_Prist) Щербаков, во всех сообщениях спрашивается о возможности, а не о «желании капризного ребенка».

Логичный ответ был бы или «такая возможность отсутствует», или «такая возможность есть…..».

PS: Если бы покупая внедорожник, Вы бы поинтересовались о возможности проехать на нем через лес, а в ответ бы Вам сказали, что можно проехать по шоссе, а Ваш вопрос это желание капризного ребенка, то чтобы Вы ответили?

Изменено: tchack20.12.2022 10:43:23

 

Дмитрий(The_Prist) Щербаков

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

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

Профессиональная разработка приложений для MS Office

#28

20.12.2022 11:04:25

Цитата
tchack написал:
Если бы покупая внедорожник, Вы бы поинтересовались о возможности проехать на нем через лес, а в ответ бы Вам сказали, что можно проехать по шоссе, а Ваш вопрос это желание капризного ребенка, то чтобы Вы ответили?

я бы ответил, что Вы сейчас фигню полную написали и с аллегориями у Вас явно проблемы. Вы не подумали о том, что лес лесу рознь? Если в лесу нет дорог — одни деревья и нет даже тропинки — какой нафиг внедорожник? Покупайте танк. А если надо через лес конкретный проехать и мне в салоне вместо дороги через лес показали нормальную дорогу — да я только спасибо им скажу, что не отправили напролом в лес.
Ну а тропинки через лес Вам показали хоть на внедорожнике, хоть на велосипеде, но Вы ищите какие-то другие. При этом чем не нравятся те, что показали — не ясно, кром того, что «ну не нравится так». Поэтому пример Ваш весьма некорректен. К тому же Вы тут не на рынке и не в салоне, чтобы с Вами кто-то любезничал и вокруг бегал, накидывая варианты просто потому, что Вам так хочется. Поясните что не так с предложенными вариантам и чем не подходят — тогда будет разговор и можно будет думать, как что-то обойти или сделать иначе.

Цитата
tchack написал:
Логичный ответ был бы или «такая возможность отсутствует», или «такая возможность есть…..».

Вам привели несколько вариантов — ни один не подошел. Логично на Вашем месте было бы пояснить почему не подходит. Но Вы не хотите — значит это именно желание/каприз, а не конкретная задача. Вот когда поясните как-то иначе, кроме «а как еще можно?», тогда может и появится еще какой-то вариант. Ибо решать задачу просто из разряда «накидайте мне разных вариантов» вряд ли кто захочет.
Научитесь читать то, что пишут, а не то, что хотите прочесть:

Цитата
Дмитрий(The_Prist) Щербаков написал:
никто не понимает почему нельзя Union и почему не подходят другие предложенные варианты.

Изменено: Дмитрий(The_Prist) Щербаков20.12.2022 11:10:03

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

tchack

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

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

#29

11.01.2023 12:18:45

Подскажите, пожалуйста, почему не работает вариант:

Код
Debug.Print WorksheetFunction.CountBlank(Sheet1.Range("Таблица1[ОДИН],Таблица1[ПЯТЬ],Таблица1[ВОСЕМЬ]"))

но работает:

Код
Debug.Print WorksheetFunction.CountBlank(Sheet1.Range("O2:O7", "R2:R7"))
 

New

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

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

#30

11.01.2023 12:43:22

потому что у вас неверная запись при обращении к объектам
P.S. Поиск костылей продолжается )

Изменено: New11.01.2023 12:44:55

VBA Columns

Excel VBA Columns Property

We all are well aware of the fact that an Excel Worksheet is arranged in columns and rows and each intersection of rows and columns is considered as a cell. Whenever we want to refer a cell in Excel through VBA, we can use the Range or Cells properties. What if we want to refer the columns from Excel worksheet? Is there any function which we can use to refer the same? The answer is a big YES!

Yes, there is a property in VBA called “Columns” which helps you in referring as well as returning the column from given Excel Worksheet. We can refer any column from the worksheet using this property and can manipulate the same.

Syntax of VBA Columns:

The syntax for VBA Columns property is as shown below:

Synatx of Columns Property

Where,

  • RowIndex – Represents the row number from which the cells have to be retrieved.
  • ColumnIndex – Represents the column number which is in an intersection with the respective rows and cells.

Obviously, which column needs to be included/used for further proceedings is being used by these two arguments. Both are optional and if not provided by default would be considered as the first row and first column.

How to Use Columns Property in Excel VBA?

Below are the different examples to use columns property in excel using VBA code.

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

Example #1 – Select Column using VBA Columns Property

We will see how a column can be selected from a worksheet using VBA Columns property. For this, follow the below steps:

Step 1: Insert a new module under Visual Basic Editor (VBE) where you can write the block of codes. Click on Insert tab and select Module in VBA pane.

Insert Module

Step 2: Define a new sub-procedure which can hold the macro you are about to write.

Code:

Sub Example_1()

End Sub

VBA Columns Example 1-2

Step 3: Use Columns.Select property from VBA to select the first column from your worksheet. This actually has different ways, you can use Columns(1).Select initially. See the screenshot below:

Code:

Sub Example_1()

Columns(1).Select

End Sub

VBA Columns Example 1-3

The Columns property in this small piece of code specifies the column number and Select property allows the VBA to select the column. Therefore in this code, Column 1 is selected based on the given inputs.

Step 4: Hit F5 or click on the Run button to run this code and see the output. You can see that column 1 will be selected in your excel sheet.

VBA Columns Example 1-4

This is one way to use columns property to select a column from a worksheet. We can also use the column names instead of column numbers in the code. Below code also gives the same result.

Code:

Sub Example_1()

Columns("A").Select

End Sub

VBA Columns Example 1-5

Example #2 – VBA Columns as a Worksheet Function

If we are using the Columns property without any qualifier, then it will only work on all the Active worksheets present in a workbook. However, in order to make the code more secure, we can use the worksheet qualifier with columns and make our code more secure. Follow the steps below:

Step 1: Define a new sub-procedure which can hold the macro under the module.

Code:

Sub Example_2()

End Sub

VBA Columns Example 2-1

Now we are going to use Worksheets.Columns property to select a column from a specified worksheet.

Step 2: Start typing the Worksheets qualifier under given macro. This qualifier needs the name of the worksheet, specify the sheet name as “Example 2” (Don’t forget to add the parentheses). This will allow the system to access the worksheet named Example 2 from the current workbook.

Code:

Sub Example_2()

Worksheets("Example 2")

End Sub

Worksheets Qualifier - Example 2

Step 3: Now use Columns property which will allow you to perform different column operations on a selected worksheet. I will choose the 4th column. I either can choose it by writing the index as 4 or specifying the column alphabet which is “D”.

Code:

Sub Example_2()

Worksheets("Example 2").Columns("D")

End Sub

VBA Columns Example 2-3

As of here, we have selected a worksheet named Example 2 and accessed the column D from it. Now, we need to perform some operations on the column accessed.

Step 4: Use Select property after Columns to select the column specified in the current worksheet.

Code:

Sub Example_2()

Worksheets("Example 2").Columns("D").Select

End Sub

Select property

Step 5: Run the code by pressing the F5 key or by clicking on Play Button.

VBA Columns Example 2-5

Example #3 – VBA Columns Property to Select Range of Cells

Suppose we want to select the range of cells across different columns. We can combine the Range as well as Columns property to do so. Follow the steps below:

Suppose we have our data spread across B1 to D4 in the worksheet as shown below:

VBA Columns Example 3-1

Step 1: Define a new sub-procedure to hold a macro.

Code:

Sub Example_3()

End Sub

VBA Columns Example 3-2

Step 2: Use the Worksheets qualifier to be able to access the worksheet named “Example 3” where we have the data shown in the above screenshot.

Code:

Sub Example_3()

Worksheets("Example 3")

End Sub

Use Worksheets qualifier

Step 3: Use Range property to set the range for this code from B1 to D4. Use the following code Range(“B1:D4”) for the same.

Code:

Sub Example_3()

Worksheets("Example 3").Range("B1:D4")

End Sub

Use Range property

Step 4: Use Columns property to access the second column from the selection. Use code as Columns(2) in order to access the second column from the accessed range.

Code:

Sub Example_3()

Worksheets("Example 3").Range("B1:D4").Columns(2)

End Sub

VBA Columns Example 3-5

Step 5: Now, the most important part. We have accessed the worksheet, range, and column. However, in order to select the accessed content, we need to use Select property in VBA. See the screenshot below for the code layout.

Code:

Sub Example_3()

Worksheets("Example 3").Range("B1:D4").Columns(2).Select

End Sub

Select property in VBA

Step 6: Run this code by hitting F5 or Run button and see the output.

VBA Columns Example 3-7

You can see the code has selected Column C from the excel worksheet though you have put the column value as 2 (which means the second column). The reason for this is, we have chosen the range as B1:D4 in this code. Which consists of three columns B, C, D. At the time of execution column B is considered as first column, C as second and D as the third column instead of their actual positionings. The range function has reduced the scope for this function for B1:D4 only.

Things to Remember

  • We can’t see the IntelliSense list of properties when we are working on VBA Columns.
  • This property is categorized under Worksheet property in VBA.

Recommended Articles

This is a guide to VBA Columns. Here we discuss how to use columns property in Excel by using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Insert Column
  2. Grouping Columns in Excel
  3. VBA Delete Column
  4. Switching Columns in Excel

Понравилась статья? Поделить с друзьями:
  • Excel vba columns value
  • Excel vba cells font color
  • Excel vba columns numbers
  • Excel vba cells find if not found
  • Excel vba column from range