Selecting all rows in excel vba

Содержание

  1. VBA – Select (and work with) Entire Rows & Columns
  2. Select Entire Rows or Columns
  3. Select Single Row
  4. Select Single Column
  5. Select Multiple Rows or Columns
  6. Select ActiveCell Row or Column
  7. Select Rows and Columns on Other Worksheets
  8. VBA Coding Made Easy
  9. Is Selecting Rows and Columns Necessary?
  10. Methods and Properties of Rows & Columns
  11. Delete Entire Rows or Columns
  12. Insert Rows or Columns
  13. Copy & Paste Entire Rows or Columns
  14. Paste Into Existing Row or Column
  15. Insert & Paste
  16. Hide / Unhide Rows and Columns
  17. Group / UnGroup Rows and Columns
  18. Set Row Height or Column Width
  19. Autofit Row Height / Column Width
  20. Rows and Columns on Other Worksheets or Workbooks
  21. Get Active Row or Column
  22. VBA Code Examples Add-in
  23. Entire Rows and Columns
  24. Range.Rows property (Excel)
  25. Syntax
  26. Remarks
  27. Example
  28. Support and feedback
  29. Свойство Range.Rows (Excel)
  30. Синтаксис
  31. Замечания
  32. Пример
  33. Поддержка и обратная связь
  34. VBA Lesson 2-6: VBA for Excel for the Cells, Rows and Columns

VBA – Select (and work with) Entire Rows & Columns

In this Article

This tutorial will demonstrate how to select and work with entire rows or columns in VBA.

First we will cover how to select entire rows and columns, then we will demonstrate how to manipulate rows and columns.

Select Entire Rows or Columns

Select Single Row

You can select an entire row with the Rows Object like this:

Or you can use EntireRow along with the Range or Cells Objects:

You can also use the Range Object to refer specifically to a Row:

Select Single Column

Instead of the Rows Object, use the Columns Object to select columns. Here you can reference the column number 3:

or letter “C”, surrounded by quotations:

Instead of EntireRow, use EntireColumn along with the Range or Cells Objects to select entire columns:

You can also use the Range Object to refer specifically to a column:

Select Multiple Rows or Columns

Selecting multiple rows or columns works exactly the same when using EntireRow or EntireColumn:

However, when you use the Rows or Columns Objects, you must enter the row numbers or column letters in quotations:

Select ActiveCell Row or Column

To select the ActiveCell Row or Column, you can use one of these lines of code:

Select Rows and Columns on Other Worksheets

In order to select Rows or Columns on other worksheets, you must first select the worksheet.

The same goes for when selecting rows or columns in other workbooks.

Note: You must Activate the desired workbook. Unlike the Sheets Object, the Workbook Object does not have a Select Method.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Is Selecting Rows and Columns Necessary?

However, it’s (almost?) never necessary to actually select Rows or Columns. You don’t need to select a Row or Column in order to interact with them. Instead, you can apply Methods or Properties directly to the Rows or Columns. The next several sections will demonstrate different Methods and Properties that can be applied.

You can use any method listed above to refer to Rows or Columns.

Methods and Properties of Rows & Columns

Delete Entire Rows or Columns

To delete rows or columns, use the Delete Method:

Insert Rows or Columns

Use the Insert Method to insert rows or columns:

Copy & Paste Entire Rows or Columns

Paste Into Existing Row or Column

When copying and pasting entire rows or columns you need to decide if you want to paste over an existing row / column or if you want to insert a new row / column to paste your data.

These first examples will copy and paste over an existing row or column:

Insert & Paste

These next examples will paste into a newly inserted row or column.

This will copy row 1 and insert it into row 5, shifting the existing rows down:

This will copy column C and insert it into column E, shifting the existing columns to the right:

Hide / Unhide Rows and Columns

To hide rows or columns set their Hidden Properties to True. Use False to hide the rows or columns:

Group / UnGroup Rows and Columns

If you want to Group rows (or columns) use code like this:

To remove the grouping use this code:

This will expand all “grouped” outline levels:

and this will collapse all outline levels:

Set Row Height or Column Width

To set the column width use this line of code:

To set the row height use this line of code:

Autofit Row Height / Column Width

To Autofit a row:

Rows and Columns on Other Worksheets or Workbooks

To interact with rows and columns on other worksheets, you must define the Sheets Object:

Similarly, to interact with rows and columns in other workbooks, you must also define the Workbook Object:

Get Active Row or Column

To get the active row or column, you can use the Row and Column Properties of the ActiveCell Object.

This also works with the Range Object:

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Entire Rows and Columns

This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?

Place a command button on your worksheet and add the following code lines:

1. The following code line selects the entire sheet.

Note: because we placed our command button on the first worksheet, this code line selects the entire first sheet. To select cells on another worksheet, you have to activate this sheet first. For example, the following code lines select the entire second worksheet.

2. The following code line selects the second column.

3. The following code line selects the seventh row.

4. To select multiple rows, add a code line like this:

5. To select multiple columns, add a code line like this:

6. Be careful not to mix up the Rows and Columns properties with the Row and Column properties. The Rows and Columns properties return a Range object. The Row and Column properties return a single value.

7. Select cell D6. The following code line selects the entire row of the active cell.

Note: border for illustration only.

8. Select cell D6. The following code line enters the value 2 into the first cell of the column that contains the active cell.

Note: border for illustration only.

9. Select cell D6. The following code line enters the value 3 into the first cell of the row below the row that contains the active cell.

Источник

Range.Rows property (Excel)

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

Syntax

expression.Rows

expression A variable that represents a Range object.

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

When applied to a Range object that is a multiple selection, this property returns rows from only the first area of the range. For example, if the Range object someRange has two areas—A1:B2 and C3:D4—, someRange.Rows.Count returns 2, not 4. To use this property on a range that may contain a multiple selection, test Areas.Count to determine whether the range is a multiple selection. If it is, loop over each area in the range, as shown in the third example.

The returned range might be outside the specified range. For example, Range(«A1:B2»).Rows(5) returns cells A5:B5. For more information, see the Item property.

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

Example

This example deletes the range B5:Z5 on Sheet1 of the active workbook.

This example deletes rows in the current region on worksheet one of the active workbook where the value of cell one in the row is the same as the value of cell one in the previous row.

This example displays the number of rows 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.Rows (Excel)

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

Синтаксис

expression. Строк

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

Замечания

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

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

Возвращаемый диапазон может находиться за пределами указанного диапазона. Например, Range(«A1:B2»).Rows(5) возвращает ячейки A5:B5. Дополнительные сведения см. в разделе Свойство Item .

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

Пример

В этом примере удаляется диапазон B5:Z5 на листе 1 активной книги.

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

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

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

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

Источник

VBA Lesson 2-6: VBA for Excel for the Cells, Rows and Columns

Here is some code to move around and work with the components (rows, columns, cells and their values and formulas) of a worksheet.

Selection and ActiveCell

The object Selection comprises what is selected. It can be a single cell, many cells, a column, a row,many of these, a chart, an image or any other object.

For example:
Range(«A1:A30»).Select
Selection.ClearContents
will remove the content (values or formulas) of the cells A1 to A30..

The ActiveCell is the selected cell or the first cell of the range that you have selected. Try this in Excel:
— select column A and see that cell A1 is not highlighted as the other cells. It is the ActiveCell.
— select row 3 and see that A3 is the ActiveCell.
— select cells D3 to G13 starting with D3 and see that D3 is the ActiveCell
— now select the same range but start with G13. So select G13 to D3 and see that G13 is the ActiveCell

The ActiveCell is a very important concept that you will need to remember as you start developing more complex procedures.

Delete or ClearContents

BEWARE: If you write Range(«a2»).Delete the cell A2 is destroyed and cell A3 becomes cell A2 and all the formulas that refer to cell A2 are scrapped. If you use Range(«a2»).ClearContents only the value of cell A2 is removed. In VBA Delete is a big word use it with moderation and only when you really mean Delete.

Cells and ClearContents

To select all cells you will use
Cells.Select
And the to clear them all you will write:
Selection.ClearContents
or without selecting all the cells you can still clear them all with:
Cells.ClearContents

To select a cell you will write:
Range
(«A1»).Select

To select a set of contiguous cells you will write:
Range («A1:A5»).Select

To select a set of non contiguous cells you will write:
Range («A1,A5,B4»).Select

Columns, Rows, Select, EntireRow, EntireColumn

To select a column you will write:
Columns(«A»).Select

To select a set of contiguous columns you will write:
Columns («A:B»).Select

To select a set of non contiguous columns you will write:
Range(«A:A,C:C,E:E»).Select

To select a row you will write:
Rows(«1»).Select

To select a set of contiguous columns you will write:
Range(«1:1,3:3,6:6»).Select

To select a set of non contiguous columns you will write:
Rows(«1:13»).Select

You can also select the column or the row with this:
ActiveCell.EntireColumn.Select
ActiveCell.EntireRow.Select
Range(«A1»).EntireColumn.Select
Range(«A1»).EntireRow.Select

If more than one cell is selected the following code will select all rows and columns covered by the selection:
Selection.EntireColumn.Select
Selection.EntireRow.Select

When you know well your way around an Excel worksheet with VBA you can transform a set of raw data into a complex report like in: «vba-example-reporting.xls«

The Offset method is the one that you will use the most. It allows you to move right, left, up and down.

For example if you want to move 3 cells to the right, you will write:
Activecell.Offset(0,3).Select

If you want to move 3 cells to the left,
Activecell.Offset(0,-3).Select
Beware though if you are in column A this line will return an error message

If you want to move three cells down:
Activecell.Offset(3,0).Select

If you want to move three cells up:
Activecell.Offset(-3,0).Select

Here is a piece of code that you will use very frequently. If you want to select one cell and three more down:
Range(Activecell,Activecell.Offset(3,0)).Select
Range(«A1» ,Range(«A1»).Offset(3,0)).Select

When you want to enter a numerical value in a cell you will write:
Range(«A1»).Select
Selection.Value = 32

Note that you don’t need to select a cell to enter a value in it, from anywhere on the sheet you can write:
Range(«A1»).Value = 32

You can even change the value of cells on another sheet with:
Sheets(«SoAndSo»).Range(«A1»).Value = 32
BEWARE: When you send a value to a cell without selecting it the cursor doesn’t move and the Activecell remains the same it doesn’t become the cell in which you have just entered a value. So if you do Activecell.Offset(1,0).Select you will not move one cell down from the cell in which you have just entered a value but from the last cell that was selected.

You can also enter the same value in many cells with:
Range(«A1:B32»).Value = 32

If you want to enter a text in a cell you need to use the double quotes like:
Range(«A1»).Value = «Peter»

If you want to enter a text within double quotes showing in a cell you need to triple the double quotes like:
Range(«A1»).Value = «»» Peter»»»

When you want to enter a formula in a cell you will write:
Range(«A1»).Select
Selection.Formula = «=C8+C9»
Note the two equal signs (=) including the one within the double quotes like if you were entering it manually.

Again you don’t need to select a cell to enter a formula in it, from anywhere on the sheet you can write:
Range(«A1»).Formula = «=C8+C9»

If you write the following:
Range(«A1:A8»).Formula = «=C8+C9»

The formula in A1 will be =C8+C9, the formula in A2 will be =C9+C10 and so on. If you want to have the exact formula =C8+C9 in all the cells, you need to write:
Range(«A1:A8»).Formula = «=$C$8+$C$9»

If you have a date in cell A1 like January, 3 2007
Range(«A2)».Value = Month(Range(«A1»).Value the value entered in A2 will be 1
Range(«A2)».Value = Day(Range(«A1»).Value
the value entered in A2 will be 3
Range(«A2)».Value = Year(Range(«A1»).Value
the value entered in A2 will be 2007

Month and MonthName

As you have seen above:
Month(A1) will return «3» if there is «3/12/2007» in A1
But:
MonthName(Range(«A1»).Value) will return «January» if there is «1» in A1
MonthName(Range(«A1»).Value,True)
will return «Feb» if there is «2» in A1
MonthName(Month(Range(«A1»).Value))
will return «March» if there is «3/12/2007» in A1

One of the most important property when working with sets of data and databases:
Selection.CurrentRegion.Select
will select all cells from the selection to the first empty row and the first empty column. See the lesson on databases to discover the importance of CurrentRegion

Column, Row, Columns, Rows, Count

For the following lines of code notice that you need to send the result into a variable. See lesson 2-9 on variables

Источник

I found a similar solution to this question in c# How to Select all the cells in a worksheet in Excel.Range object of c#?

What is the process to do this in VBA?

I select data normally by using «ctrl+shift over arrow, down arrow» to select an entire range of cells. When I run this in a macro it codes out A1:Q398247930, for example. I need it to just be

.SetRange Range("A1:whenever I run out of rows and columns")

I could easily do it myself without a macro, but I’m trying to make the entire process a macro, and this is just a piece of it.

Sub sort()
    'sort Macro
    Range("B2").Select
    ActiveWorkbook.Worksheets("Master").sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Master").sort.SortFields.Add Key:=Range("B2"), _
      SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Master").sort
        .SetRange Range("A1:whenever I run out of rows and columns")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

edit:
There are other parts where I might want to use the same code but the range is say «C3:End of rows & columns». Is there a way in VBA to get the location of the last cell in the document?

asked Jul 30, 2013 at 18:50

C. Tewalt's user avatar

C. TewaltC. Tewalt

2,2612 gold badges29 silver badges47 bronze badges

I believe you want to find the current region of A1 and surrounding cells — not necessarily all cells on the sheet.
If so — simply use…
Range(«A1»).CurrentRegion

answered Jul 30, 2013 at 19:17

ExcelExpert's user avatar

ExcelExpertExcelExpert

3522 silver badges4 bronze badges

1

You can simply use cells.select to select all cells in the worksheet. You can get a valid address by saying Range(Cells.Address).

If you want to find the last Used Range where you have made some formatting change or entered a value into you can call ActiveSheet.UsedRange and select it from there. Hope that helps.

June7's user avatar

June7

19.5k8 gold badges24 silver badges33 bronze badges

answered Jul 30, 2013 at 19:11

chancea's user avatar

chanceachancea

5,8083 gold badges28 silver badges39 bronze badges

2

you can use all cells as a object like this :

Dim x as Range
Set x = Worksheets("Sheet name").Cells

X is now a range object that contains the entire worksheet

answered Apr 15, 2015 at 11:47

user4791681's user avatar

you have a few options here:

  1. Using the UsedRange property
  2. find the last row and column used
  3. use a mimic of shift down and shift right

I personally use the Used Range and find last row and column method most of the time.

Here’s how you would do it using the UsedRange property:

Sheets("Sheet_Name").UsedRange.Select

This statement will select all used ranges in the worksheet, note that sometimes this doesn’t work very well when you delete columns and rows.

The alternative is to find the very last cell used in the worksheet

Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
    Range(Cells(1, 1), rngTemp).Select
End If

What this code is doing:

  1. Find the last cell containing any value
  2. select cell(1,1) all the way to the last cell

Faisal Mehmood's user avatar

answered Jul 30, 2013 at 20:32

Derek Cheng's user avatar

Derek ChengDerek Cheng

5353 silver badges8 bronze badges

3

Another way to select all cells within a range, as long as the data is contiguous, is to use Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select.

answered Mar 29, 2019 at 19:38

Bob the Builder's user avatar

I would recommend recording a macro, like found in this post;

Excel VBA macro to filter records

But if you are looking to find the end of your data and not the end of the workbook necessary, if there are not empty cells between the beginning and end of your data, I often use something like this;

R = 1
Do While Not IsEmpty(Sheets("Sheet1").Cells(R, 1))
    R = R + 1
Loop
Range("A5:A" & R).Select 'This will give you a specific selection

You are left with R = to the number of the row after your data ends. This could be used for the column as well, and then you could use something like Cells(C , R).Select, if you made C the column representation.

Community's user avatar

answered Jul 30, 2013 at 19:25

MakeCents's user avatar

MakeCentsMakeCents

7321 gold badge5 silver badges15 bronze badges

2

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A1", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

answered Mar 14, 2017 at 20:57

Yehia Amer's user avatar

Yehia AmerYehia Amer

5985 silver badges11 bronze badges

Here is what I used, I know it could use some perfecting, but I think it will help others…

''STYLING''

Dim sheet As Range

' Find Number of rows used
Dim Final As Variant
    Final = Range("A1").End(xlDown).Row

' Find Last Column
Dim lCol As Long
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

Set sheet = ActiveWorkbook.ActiveSheet.Range("A" & Final & "", Cells(1, lCol ))
With sheet
    .Interior.ColorIndex = 1
End With

answered Mar 16, 2019 at 4:29

FreeSoftwareServers's user avatar

I have found that the Worksheet «.UsedRange» method is superior in many instances to solve this problem.
I struggled with a truncation issue that is a normal behaviour of the «.CurrentRegion» method. Using [ Worksheets(«Sheet1»).Range(«A1»).CurrentRegion ] does not yield the results I desired when the worksheet consists of one column with blanks in the rows (and the blanks are wanted). In this case, the «.CurrentRegion» will truncate at the first record. I implemented a work around but recently found an even better one; see code below that allows copying the whole set to another sheet or to identify the actual address (or just rows and columns):

Sub mytest_GetAllUsedCells_in_Worksheet()
    Dim myRange

    Set myRange = Worksheets("Sheet1").UsedRange
    'Alternative code:  set myRange = activesheet.UsedRange

   'use msgbox or debug.print to show the address range and counts
   MsgBox myRange.Address      
   MsgBox myRange.Columns.Count
   MsgBox myRange.Rows.Count

  'Copy the Range of data to another sheet
  'Note: contains all the cells with that are non-empty
   myRange.Copy (Worksheets("Sheet2").Range("A1"))
   'Note:  transfers all cells starting at "A1" location.  
   '       You can transfer to another area of the 2nd sheet
   '       by using an alternate starting location like "C5".

End Sub

answered May 2, 2019 at 19:38

Lifygen's user avatar

Maybe this might work:

Sh.Range(«A1», Sh.Range(«A» & Rows.Count).End(xlUp))

answered Oct 31, 2014 at 18:38

Sarah's user avatar

Refering to the very first question, I am looking into the same.
The result I get, recording a macro, is, starting by selecting cell A76:

Sub find_last_row()
    Range("A76").Select
    Range(Selection, Selection.End(xlDown)).Select
End Sub

answered Aug 7, 2015 at 12:40

Pavlin Todorov's user avatar


VBA Select

It is very common to find the .Select methods in saved macro recorder code, next to a Range object.

.Select is used to select one or more elements of Excel (as can be done by using the mouse) allowing further manipulation of them.

Selecting cells with the mouse:

Select with the Mouse

Selecting cells with VBA:

    'Range([cell1],[cell2])
    Range(Cells(1, 1), Cells(9, 5)).Select
    Range("A1", "E9").Select
    Range("A1:E9").Select

Each of the above lines select the range from «A1» to «E9».

Select with VBA


VBA Select CurrentRegion

If a region is populated by data with no empty cells, an option for an automatic selection is the CurrentRegion property alongside the .Select method.

CurrentRegion.Select will select, starting from a Range, all the area populated with data.

    Range("A1").CurrentRegion.Select

CurrentRegion

Make sure there are no gaps between values, as CurrentRegion will map the region through adjoining cells (horizontal, vertical and diagonal).

  Range("A1").CurrentRegion.Select

With all the adjacent data

CurrentRegion Data

Not all adjacent data

CurrentRegion Missing Data

«C4» is not selected because it is not immediately adjacent to any filled cells.


VBA ActiveCell

The ActiveCell property brings up the active cell of the worksheet.

In the case of a selection, it is the only cell that stays white.

A worksheet has only one active cell.

    Range("B2:C4").Select
    ActiveCell.Value = "Active"

ActiveCell

Usually the ActiveCell property is assigned to the first cell (top left) of a Range, although it can be different when the selection is made manually by the user (without macros).

ActiveCell Under

The AtiveCell property can be used with other commands, such as Resize.


VBA Selection

After selecting the desired cells, we can use Selection to refer to it and thus make changes:

    Range("A1:D7").Select
    Selection = 7

Example Selection

Selection also accepts methods and properties (which vary according to what was selected).

    Selection.ClearContents 'Deletes only the contents of the selection
    Selection.Interior.Color = RGB(255, 255, 0) 'Adds background color to the selection

Clear Selection

As in this case a cell range has been selected, the Selection will behave similarly to a Range. Therefore, Selection should also accept the .Interior.Color property.

RGB (Red Green Blue) is a color system used in a number of applications and languages. The input values for each color, in the example case, ranges from 0 to 255.


Selection FillDown

If there is a need to replicate a formula to an entire selection, you can use the .FillDown method

    Selection.FillDown

Before the FillDown

Before Filldown

After the FillDown

After FillDown

.FillDown is a method applicable to Range. Since the Selection was done in a range of cells (equivalent to a Range), the method will be accepted.

.FillDown replicates the Range/Selection formula of the first line, regardless of which ActiveCell is selected.

.FillDown can be used at intervals greater than one column (E.g. Range(«B1:C2»).FillDown will replicate the formulas of B1 and C1 to B2 and C2 respectively).


VBA EntireRow and EntireColumn

You can select one or multiple rows or columns with VBA.

    Range("B2").EntireRow.Select
    Range("C3:D3").EntireColumn.Select

Select EntireColumn

The selection will always refer to the last command executed with Select.

To insert a row use the Insert method.

    Range("A7").EntireRow.Insert
    'In this case, the content of the seventh row will be shifted downward

To delete a row use the Delete method.

    Range("A7").EntireRow.Delete
    'In this case, the content of the eighth row will be moved to the seventh

VBA Rows and Columns

Just like with the EntireRow and EntireColumn property, you can use Rows and Columns to select a row or column.

    Columns(5).Select
    Rows(3).Select

Select Rows

To hide rows:

    Range("A1:C3").Rows.Hidden = True

Hidden Cells

In the above example, rows 1 to 3 of the worksheet were hidden.


VBA Row and Column

Row and Column are properties that are often used to obtain the numerical address of the first row or first column of a selection or a specific cell.

    Range("A3:H30").Row 'Referring to the row; returns 3
    Range("B3").Column  'Referring to the column; returns 2

The results of Row and Column are often used in loops or resizing.



Consolidating Your Learning

Suggested Exercise



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

Sometimes you’ll want to select entire rows or columns, or even every cell in
a worksheet.  Here’s how:

Selecting Columns

You can do this using the Columns collection.  For
example:

Sub SelectColumns()

Columns(«B»).Select

Columns(«B:D»).Select

End Sub

The above macro would select column B, then columns
B
through to D:

Columns B to D selected

The result of running the above macro.

Note that you can select a single column by number too — for example,
Columns(2).Select
— but this method doesn’t work for a range of
columns.

Selecting Rows

You can select rows in the same way, but using the Rows
collection:

Sub SelectRows()

Rows(«2»).Select

Rows(«2:4»).Select

End Sub

The above routine would leave rows 2 through to 4 selected:

Rows 2 to 4 selected

The results of running the macro above.

Note that as for columns you can dispense with the quotation marks if you’re
selecting a single row.  So Rows(2).Select would also
select the second row.

 Selecting Every Cell in a Worksheet

In Excel you can select every single cell by clicking on the square at the
top left corner of a worksheet:

Selecting every cell

Click on the square shown to select every cell in a worksheet.

The VBA equivalent command to select every single cell in a sheet is:

Having seen how to select cells, rows and columns, it’s time to complete the
picture by showing some of the less commonly used selection commands. 

Понравилась статья? Поделить с друзьями:
  • Selecting all images in word
  • Selecting all data in excel
  • Selecting a sentence in word
  • Selecting a paragraph in word
  • Select в таблицу excel