Columns vba excel что это такое

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

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

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


title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Range.Columns property (Excel)

vbaxl10.chm144101

vbaxl10.chm144101

excel

Excel.Range.Columns

a1a23288-e911-909d-0bc0-48bdce2ccbac

05/10/2019

medium

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.

Remarks

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).

Range("myRange").Columns(1).Value = 0

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.

Public Sub ShowNumberOfColumnsInSheet1Selection
   Worksheets("Sheet1").Activate 
   
   Dim selectedRange As Excel.Range
   Set selectedRange = Selection
   
   Dim areaCount As Long
   areaCount = Selection.Areas.Count 
   
   If areaCount <= 1 Then 
      MsgBox "The selection contains " & _ 
             Selection.Columns.Count & " columns." 
   Else 
      Dim areaIndex As Long
      areaIndex = 1 
      For Each area In Selection.Areas 
         MsgBox "Area " & areaIndex & " of the selection contains " & _ 
                area.Columns.Count & " columns." 
         areaIndex = areaIndex + 1 
      Next 
   End If
End Sub

[!includeSupport and feedback]

Содержание

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

Свойство 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 и обратная связь.

Источник

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.

Источник

Refer to Rows and Columns

Use the Rows property or the Columns property to work with entire rows or columns. These properties return a Range object that represents a range of cells. In the following example, Rows(1) returns row one on Sheet1. The Bold property of the Font object for the range is then set to True.

The following table illustrates some row and column references using the Rows and Columns properties.

Reference Meaning
Rows(1) Row one
Rows All the rows on the worksheet
Columns(1) Column one
Columns(«A») Column one
Columns All the columns on the worksheet

To work with several rows or columns at the same time, create an object variable and use the Union method, combining multiple calls to the Rows or Columns property. The following example changes the format of rows one, three, and five on worksheet one in the active workbook to bold.

Sample code provided by: Dennis Wallentin, VSTO & .NET & Excel This example deletes the empty rows from a selected range.

This example deletes the empty columns from a selected range.

About the Contributor

Dennis Wallentin is the author of VSTO & .NET & Excel, a blog that focuses on .NET Framework solutions for Excel and Excel Services. Dennis has been developing Excel solutions for over 20 years and is also the coauthor of «Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft Excel, VBA and .NET (2nd Edition).»

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.

Источник

Понравилась статья? Поделить с друзьями:
  • Columns to one column excel vba
  • Columns select vba excel
  • Columns on one page in word
  • Columns not adding in excel
  • Columns meaning in excel