Vba excel добавление строк в таблицу

Вставка диапазона со сдвигом ячеек вправо или вниз методом Insert объекта Range. Вставка и перемещение строк и столбцов из кода VBA Excel. Примеры.

Range.Insert – это метод, который вставляет диапазон пустых ячеек (в том числе одну ячейку) на рабочий лист Excel в указанное место, сдвигая существующие в этом месте ячейки вправо или вниз. Если в буфере обмена содержится объект Range, то вставлен будет он со своими значениями и форматами.

Синтаксис

Expression.Insert(Shift, CopyOrigin)

Expression – выражение (переменная), возвращающее объект Range.

Параметры

Параметр Описание Значения
Shift Необязательный параметр. Определяет направление сдвига ячеек. Если параметр Shift опущен, направление выбирается в зависимости от формы* диапазона. xlShiftDown (-4121) – ячейки сдвигаются вниз;
xlShiftToRight (-4161) – ячейки сдвигаются вправо.
CopyOrigin Необязательный параметр. Определяет: из каких ячеек копировать формат. По умолчанию формат копируется из ячеек сверху или слева. xlFormatFromLeftOrAbove (0) – формат копируется из ячеек сверху или слева;
xlFormatFromRightOrBelow (1) – формат копируется из ячеек снизу или справа.

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

Примеры

Простая вставка диапазона

Вставка диапазона ячеек в диапазон «F5:K9» со сдвигом исходных ячеек вправо:

Range(«F5:K9»).Insert Shift:=xlShiftToRight

Если бы параметр Shift не был указан, сдвиг ячеек, по умолчанию, произошел бы вниз, так как диапазон горизонтальный.

Вставка вырезанного диапазона

Вставка диапазона, вырезанного в буфер обмена методом Range.Cut, из буфера обмена со сдвигом ячеек по умолчанию:

Range(«A1:B6»).Cut

Range(«D2»).Insert

Обратите внимание, что при использовании метода Range.Cut, точка вставки (в примере: Range("D2")) не может находится внутри вырезанного диапазона, а также в строке или столбце левой верхней ячейки вырезанного диапазона вне вырезанного диапазона (в примере: строка 1 и столбец «A»).

Вставка скопированного диапазона

Вставка диапазона, скопированного в буфер обмена методом Range.Copy, из буфера обмена со сдвигом ячеек по умолчанию:

Range(«B2:D10»).Copy

Range(«F2»).Insert

Обратите внимание, что при использовании метода Range.Copy, точка вставки (в примере: Range("F2")) не может находится внутри скопированного диапазона, но в строке или столбце левой верхней ячейки скопированного диапазона вне скопированного диапазона находится может.

Вставка и перемещение строк

Вставка одной строки на место пятой строки со сдвигом исходной строки вниз:


Вставка четырех строк на место пятой-восьмой строк со сдвигом исходных строк вниз:


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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Sub Primer1()

Dim n As Long, k As Long, s As String

‘Номер строки, над которой необходимо вставить строки

n = 8

‘Количесто вставляемых строк

k = 4

‘Указываем адрес диапазона строк

s = n & «:» & (n + k 1)

‘Вставляем строки

Rows(s).Insert

End Sub

‘или то же самое с помощью цикла

Sub Primer2()

Dim n As Long, k As Long, i As Long

n = 8

k = 4

    For i = 1 To k

        Rows(n).Insert

    Next

End Sub


Перемещение второй строки на место шестой строки:

Rows(2).Cut

Rows(6).Insert

Вторая строка окажется на месте пятой строки, так как третья строка заместит вырезанную вторую строку, четвертая встанет на место третьей и т.д.


Перемещение шестой строки на место второй строки:

Rows(6).Cut

Rows(2).Insert

В этом случае шестая строка окажется на месте второй строки.

Вставка и перемещение столбцов

Вставка одного столбца на место четвертого столбца со сдвигом исходного столбца вправо:


Вставка трех столбцов на место четвертого-шестого столбцов со сдвигом исходных столбцов вправо:


Перемещение третьего столбца на место седьмого столбца:

Columns(3).Cut

Columns(7).Insert

Третий столбец окажется на месте шестого столбца, так как четвертый столбец заместит вырезанный третий столбец, пятый встанет на место четвертого и т.д.


Перемещение седьмого столбца на место третьего столбца:

Columns(7).Cut

Columns(3).Insert

В этом случае седьмой столбец окажется на месте третьего столбца.


VBA Add row to Table in Excel. We can add a single row or multiple rows and data to table. Default new rows added at the end of the table. In this tutorial we have explained multiple examples with explanation. We also shown example output screenshots. We have specified three examples in the following tutorial. You can change table and sheet name as per your requirement. We also specified step by step instructions how to run VBA macro code at the end of the session.

Table of Formats:

  • Objective
  • Syntax to Add Row to Table using VBA in Excel
  • Example to Add New Row to Table on the Worksheet in Excel
  • Add Multiple Rows to Table in Excel using VBA
  • Add Row & Data to Table on the Worksheet in Excel
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Syntax to Add Row to Table using VBA in Excel

Here is the syntax to add new row to table on the worksheet using VBA in Excel.

expression.Add(Position, AlwaysInsert)

Where expression represents the ListRows.
Position is an optional parameter. It represents the relative position of the new row. Accepts the Integer value.
AlwaysInsert is an optional parameter. It represents the cells to be shifted to down or not, based on Boolean value. Accepts the Boolean value either True or False.

Note: If position is not specified, default adds new row at the end of the table.

Example to Add New Row to Table on the Worksheet

Let us see the example to add new row to table on the worksheet. The sheet name defined as ‘Table‘. And we use table name as ‘MyDynamicTable‘. You can change these two as per your requirement. We Add method of the ListObject object.

 'VBA Add New Row to Table
Sub VBAF1_Add_Row_to_Table()
    
    'Declare Variables
    Dim oSheetName As Worksheet
    Dim sTableName As String
    Dim loTable As ListObject
    
    'Define Variable
    sTableName = "MyDynamicTable"
    
    'Define WorkSheet object
    Set oSheetName = Sheets("Table")
    
    'Define Table Object
    Set loTable = oSheetName.ListObjects(sTableName)
    
    'Add New row to the table
    loTable.ListRows.Add
       
End Sub

Output: Here is the following output screenshot of above example macro VBA code.

VBA Add Row to Table in Excel

Add Multiple Rows to Table in Excel using VBA

Here is another example to add multiple rows to table. In this example we add five(5) rows to the table. You can specify the number of rows count in the for loop.

'VBA Add Multiple Rows to Table
Sub VBAF1_Add_Multiple_Rows_to_Table()
    
    'Declare Variables
    Dim oSheetName As Worksheet
    Dim sTableName As String
    Dim loTable As ListObject
    Dim iCnt As Integer
    
    'Define Variable
    sTableName = "MyDynamicTable"
    
    'Define WorkSheet object
    Set oSheetName = Sheets("Table")
    
    'Define Table Object
    Set loTable = oSheetName.ListObjects(sTableName)
    
    For iCnt = 1 To 5 'You can change based on your requirement
        'Add multiple rows to the table
        loTable.ListRows.Add
    Next
    
End Sub

Output: Let us see the following output screenshot of above example macro VBA code.

VBA Add Multiple Rows to Table

Add Row & Data to Table on the Worksheet in Excel

Let us see how to add new row and data to the table using VBA in Excel. In the below example we add new row and data of 5 columns.

 'VBA Add Row and Data to Table
Sub VBAF1_Add_Row_And_Data_to_Table()
    
    'Declare Variables
    Dim oSheetName As Worksheet
    Dim sTableName As String
    Dim loTable As ListObject
    Dim lrRow As ListRow
    
    'Define Variable
    sTableName = "MyDynamicTable"
    
    'Define WorkSheet object
    Set oSheetName = Sheets("Table")
    
    'Define Table Object
    Set loTable = oSheetName.ListObjects(sTableName)
    
    'Add New row to the table
    Set lrRow = loTable.ListRows.Add
    
    'Add Data to recently added row
    With lrRow
        .Range(1) = 20
        .Range(2) = 30
        .Range(3) = 40
        .Range(4) = 50
        .Range(5) = 60
    End With
       
End Sub

Output: Here is the following output screenshot of above example VBA macro code.

VBA Add New Row and Data to Table in Excel

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel VBA Tables and ListObjects

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

I have an excel which serves to record the food you ingest for a specific day and meal. I hav a grid in which each line represent a food you ate, how much sugar it has, etc.

Then i’ve added an save button to save all the data to a table in another sheet.

This is what i have tried

    Public Sub addDataToTable(ByVal strTableName As String, ByRef arrData As Variant)
    Dim lLastRow As Long
    Dim iHeader As Integer
    Dim iCount As Integer

    With Worksheets(4).ListObjects(strTableName)
        'find the last row of the list
        lLastRow = Worksheets(4).ListObjects(strTableName).ListRows.Count

        'shift from an extra row if list has header
        If .Sort.Header = xlYes Then
            iHeader = 1
        Else
            iHeader = 0
        End If
    End With

    'Cycle the array to add each value
    For iCount = LBound(arrData) To UBound(arrData)
        **Worksheets(4).Cells(lLastRow + 1, iCount).Value = arrData(iCount)**
    Next iCount
End Sub

but i keep getting the same error on the highlighted line:

Application-defined or object-defined error

What i am doing wrong?

Thanks in advance!

Siddharth Rout's user avatar

asked Sep 6, 2012 at 10:11

Miguel Teixeira's user avatar

Miguel TeixeiraMiguel Teixeira

7731 gold badge10 silver badges29 bronze badges

You don’t say which version of Excel you are using. This is written for 2007/2010 (a different apprach is required for Excel 2003 )

You also don’t say how you are calling addDataToTable and what you are passing into arrData.
I’m guessing you are passing a 0 based array. If this is the case (and the Table starts in Column A) then iCount will count from 0 and .Cells(lLastRow + 1, iCount) will try to reference column 0 which is invalid.

You are also not taking advantage of the ListObject. Your code assumes the ListObject1 is located starting at row 1. If this is not the case your code will place the data in the wrong row.

Here’s an alternative that utilised the ListObject

Sub MyAdd(ByVal strTableName As String, ByRef arrData As Variant)
    Dim Tbl As ListObject
    Dim NewRow As ListRow

    ' Based on OP 
    ' Set Tbl = Worksheets(4).ListObjects(strTableName)
    ' Or better, get list on any sheet in workbook
    Set Tbl = Range(strTableName).ListObject
    Set NewRow = Tbl.ListRows.Add(AlwaysInsert:=True)

    ' Handle Arrays and Ranges
    If TypeName(arrData) = "Range" Then
        NewRow.Range = arrData.Value
    Else
        NewRow.Range = arrData
    End If
End Sub

Can be called in a variety of ways:

Sub zx()
    ' Pass a variant array copied from a range
    MyAdd "MyTable", [G1:J1].Value
    ' Pass a range
    MyAdd "MyTable", [G1:J1]
    ' Pass an array
    MyAdd "MyTable", Array(1, 2, 3, 4)
End Sub

answered Sep 6, 2012 at 11:06

chris neilsen's user avatar

chris neilsenchris neilsen

52.2k10 gold badges84 silver badges122 bronze badges

6

Tbl.ListRows.Add doesn’t work for me and I believe lot others are facing the same problem. I use the following workaround:

    'First check if the last row is empty; if not, add a row
    If table.ListRows.count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.count).Range
        For col = 1 To lastRow.Columns.count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                lastRow.Cells(1, col).EntireRow.Insert
                'Cut last row and paste to second last
                lastRow.Cut Destination:=table.ListRows(table.ListRows.count - 1).Range
                Exit For
            End If
        Next col
    End If

    'Populate last row with the form data
    Set lastRow = table.ListRows(table.ListRows.count).Range
    Range("E7:E10").Copy
    lastRow.PasteSpecial Transpose:=True
    Range("E7").Select
    Application.CutCopyMode = False

Hope it helps someone out there.

answered Mar 25, 2013 at 10:22

user1058322's user avatar

1

I had the same error message and after lots of trial and error found out that it was caused by an advanced filter which was set on the ListObject.
After clearing the advanced filter .listrows.add worked fine again.
To clear the filter I use this — no idea how one could clear the filter only for the specific listobject instead of the complete worksheet.

Worksheets("mysheet").ShowAllData

answered Dec 4, 2014 at 17:18

kskoeld's user avatar

1

I actually just found that if you want to add multiple rows below the selection in your table
Selection.ListObject.ListRows.Add AlwaysInsert:=True works really well. I just duplicated the code five times to add five rows to my table

answered Sep 28, 2015 at 20:16

fireball8931's user avatar

I had the same problem before and i fixed it by creating the same table in a new sheet and deleting all the name ranges associated to the table, i believe whene you’re using listobjects you’re not alowed to have name ranges contained within your table hope that helps thanks

answered Jun 25, 2017 at 20:13

Djamel Ben's user avatar

0

Ran into this issue today (Excel crashes on adding rows using .ListRows.Add).
After reading this post and checking my table, I realized the calculations of the formula’s in some of the cells in the row depend on a value in other cells.
In my case of cells in a higher column AND even cells with a formula!

The solution was to fill the new added row from back to front, so calculations would not go wrong.

Excel normally can deal with formula’s in different cells, but it seems adding a row in a table kicks of a recalculation in order of the columns (A,B,C,etc..).

Hope this helps clearing issues with .ListRows.Add

rink.attendant.6's user avatar

answered Sep 4, 2018 at 12:35

ErikB's user avatar

As using ListRow.Add can be a huge bottle neck, we should only use it if it can’t be avoided.
If performance is important to you, use this function here to resize the table, which is quite faster than adding rows the recommended way.

Be aware that this will overwrite data below your table if there is any!

This function is based on the accepted answer of Chris Neilsen

Public Sub AddRowToTable(ByRef tableName As String, ByRef data As Variant)
    Dim tableLO As ListObject
    Dim tableRange As Range
    Dim newRow As Range

    Set tableLO = Range(tableName).ListObject
    tableLO.AutoFilter.ShowAllData

    If (tableLO.ListRows.Count = 0) Then
        Set newRow = tableLO.ListRows.Add(AlwaysInsert:=True).Range
    Else
        Set tableRange = tableLO.Range
        tableLO.Resize tableRange.Resize(tableRange.Rows.Count + 1, tableRange.Columns.Count)
        Set newRow = tableLO.ListRows(tableLO.ListRows.Count).Range
    End If

    If TypeName(data) = "Range" Then
        newRow = data.Value
    Else
        newRow = data
    End If
End Sub

answered Apr 25, 2017 at 23:41

Jonas_Hess's user avatar

Jonas_HessJonas_Hess

1,8241 gold badge20 silver badges32 bronze badges

1

Just delete the table and create a new table with a different name. Also Don’t delete entire row for that table. It seems when entire row containing table row is delete it damages the DataBodyRange is damaged

answered Jun 11, 2016 at 13:19

Bhanu Sinha's user avatar

Bhanu SinhaBhanu Sinha

1,51612 silver badges10 bronze badges

Excel VBA Tutorial about how to insert rows with macrosIn certain cases, you may need to automate the process of inserting a row (or several rows) in a worksheet. This is useful, for example, when you’re (i) manipulating or adding data entries, or (ii) formatting a worksheet that uses blank rows for organization purposes.

The information and examples in this VBA Tutorial should allow you to insert rows in a variety of circumstances.

This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by clicking the button below.

Get immediate free access to the Excel VBA Insert Row workbook examples

Use the following Table of Contents to navigate to the section you’re interested in.

Insert Rows in Excel

When working manually with Excel, you can insert rows in the following 2 steps:

  1. Select the row or rows above which to insert the row or rows.
  2. Do one of the following:
    1. Right-click and select Insert.
    2. Go to Home > Insert > Insert Sheet Rows.
    3. Use the “Ctrl + Shift + +” keyboard shortcut.

Select rows; right-click; Insert

You can use the VBA constructs and structures I describe below to automate this process to achieve a variety of results.

Excel VBA Constructs to Insert Rows

Insert Rows with the Range.Insert Method

Purpose of Range.Insert

Use the Range.Insert method to insert a cell range into a worksheet. The 2 main characteristics of the Range.Insert method are the following:

  1. Range.Insert can insert a single cell or a cell range. For purposes of this VBA Tutorial, you’re interested in inserting entire rows.
  2. To make space for the newly-inserted cells, Range.Insert shifts other cells away.

Syntax of Range.Insert

expression.Insert(Shift, CopyOrigin)

“expression” is a Range object. Therefore, I simplify as follows:

Range.Insert(Shift, CopyOrigin)

Parameters of Range.Insert

  1. Parameter: Shift.
    • Description: Specifies the direction in which cells are shifted away to make space for the newly-inserted row.
    • Optional/Required: Optional.
    • Data type: Variant.
    • Values: Use a constant from the xlInsertShiftDirection Enumeration:
      • xlShiftDown or -4121: Shifts cells down.
      • xlShiftToRight or -4161: Shifts cells to the right.
    • Default: Excel decides based on the range’s shape.
    • Usage notes: When you insert a row: (i) use xlShiftDown or -4121, or (ii) omit parameter and rely on the default behavior.
  2. Parameter: CopyOrigin.
    • Description: Specifies from where (the origin) is the format for the cells in the newly inserted row copied.
    • Optional/Required: Optional.
    • Data type: Variant.
    • Values: A constant from the xlInsertFormatOrigin Enumeration:
      • xlFormatFromLeftOrAbove or 0: Newly-inserted cells take formatting from cells above or to the left.
      • xlFormatFromRightOrBelow or 1: Newly-inserted cells take formatting from cells below or to the right.
    • Default: xlFormatFromLeftOrAbove or 0. Newly-inserted cells take the formatting from cells above or to the left.

How to Use Range.Insert to Insert Rows

Use the Range.Insert method to insert a row into a worksheet. Use a statement with the following structure:

Range.Insert Shift:=xlShiftDown CopyOrigin:=xlInsertFormatOriginConstant

For these purposes:

  • Range: Range object representing an entire row. Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents the entire row. Please refer to the sections about the Rows and EntireRow properties below.
  • xlInsertFormatOriginConstant: xlFormatFromLeftOrAbove or xlFormatFromRightOrBelow. xlFormatFromLeftOrAbove is the default value. Therefore, when inserting rows with formatting from row above, you can usually omit the CopyOrigin parameter.

You can usually omit the Shift parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Specify Rows with the Worksheet.Rows Property

Purpose of Worksheet.Rows

Use the Worksheet.Rows property to return a Range object representing all the rows within the worksheet the property works with.

Worksheet.Rows is read-only.

Syntax of Worksheet.Rows

expression.Rows

“expression” is a Worksheet object. Therefore, I simplify as follows:

Worksheet.Rows

How to Use Worksheet.Rows to Insert Rows

Use the Worksheet.Rows property to specify the row or rows above which new rows are inserted.

To insert a row, use a statement with the following structure:

Worksheets.Rows(row#).Insert

“row#” is the number of the row above which the row is inserted.

To insert multiple rows, use a statement with the following structure:

Worksheet.Rows("firstRow#:lastRow#").Insert

“firstRow#” is the row above which the rows are inserted. The number of rows VBA inserts is calculated as follows:

lastRow# - firstRow# + 1

Specify the Active Cell with the Application.ActiveCell Property

Purpose of Application.ActiveCell

Use the Application.ActiveCell property to return a Range object representing the active cell.

Application.ActiveCell is read-only.

Syntax of Application.ActiveCell

expression.ActiveCell

“expression” is the Application object. Therefore, I simplify as follows:

Application.ActiveCell

How to Use Application.ActiveCell To Insert Rows

When you insert a row, use the Application.ActiveCell property to return the active cell. This allows you to use the active cell as reference for the row insertion operation.

Use the Range.Offset property to return a Range object a specific number of rows above or below the active cell. Use the Range.EntireRow property to return a Range object representing the entire row or rows above which to insert the new row. Please refer to the sections about the Offset and EntireRow properties below.

To insert a row above the active cell, use the following statement:

ActiveCell.EntireRow.Insert Shift:=xlShiftDown

To insert a row a specific number of rows above or below the active cell, use a statement with the following structure:

ActiveCell.Offset(RowOffset).EntireRow.Insert Shift:=xlShiftDown

Specify a Cell Range with the Worksheet.Range Property

Purpose of Worksheet.Range

Use the Worksheet.Range property to return a Range object representing a single cell or a cell range.

Syntax of Worksheet.Range

expression.Range(Cell1, Cell2)

“expression” is a Worksheet object. Therefore, I simplify as follows:

Worksheet.Range(Cell1, Cell2)

Parameters of Worksheet.Range

  1. Parameter: Cell1.
    • Description:
      • If you use Cell1 alone (omit Cell2), Cell1 specifies the cell range.
      • If you use Cell1 and Cell2, Cell1 specifies the cell in the upper-left corner of the cell range.
    • Required/Optional: Required.
    • Data type: Variant.
    • Values:
      • If you use Cell1 alone (omit Cell2): (i) range address as an A1-style reference in language of macro, or (ii) range name.
      • If you use Cell1 and Cell2: (i) Range object, (ii) range address, or (iii) range name.
  2. Parameter: Cell2.
    • Description: Cell in the lower-right corner of the cell range.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values: (i) Range object, (ii) range address, or (iii) range name.

How to Use Worksheet.Range to Insert Rows

When you insert a row, use the Worksheet.Range property to return a cell or cell range. This allows you to use a specific cell or cell range as reference for the row insertion operation.

Use the Range.Offset property to return a Range object a specific number of rows above or below the cell or cell range. Use the Range.EntireRow property to return a Range object representing the entire row or rows above which to insert the new row or rows. Please refer to the sections about the Offset and EntireRow properties below.

To insert rows above the cell range specified by Worksheet.Range, use a statement with the following structure:

Worksheet.Range(Cell1, Cell2).EntireRow.Insert Shift:=xlShiftDown

To insert rows a specific number of rows above or below the cell range specified by Worksheet.Range use a statement with the following structure:

Worksheet.Range(Cell1, Cell2).Offset(RowOffset).EntireRow.Insert Shift:=xlShiftDown

If the cell range represented by the Worksheet.Range property spans more than 1 row, the Insert method inserts several rows. The number of rows inserted is calculated as follows:

lastRow# - firstRow# + 1

Please refer to the section about the Worksheet.Rows property above for further information about this calculation.

Specify a Cell with the Worksheet.Cells and Range.Item Properties

Purpose of Worksheet.Cells and Range.Item

Use the Worksheet.Cells property to return a Range object representing all the cells within a worksheet.

Once your macro has all the cells within the worksheet, use the Range.Item property to return a Range object representing one of those cells.

Syntax of Worksheet.Cells and Range.Item

Worksheet.Cells
expression.Cells

“expression” is a Worksheet object. Therefore, I simplify as follows:

Worksheet.Cells
Range.Item
expression.Item(RowIndex, ColumnIndex)

“expression” is a Range object. Therefore, I simplify as follows:

Range.Item(RowIndex, ColumnIndex)
Worksheet.Cells and Range.Item Together

Considering the above:

Worksheet.Cells.Item(RowIndex, ColumnIndex)

However, Item is the default property of the Range object. Therefore, you can generally omit the Item keyword before specifying the RowIndex and ColumnIndex arguments. I simplify as follows:

Worksheet.Cells(RowIndex, ColumnIndex)

Parameters of Worksheet.Cells and Range.Item

  1. Parameter: RowIndex.
    • Description:
      • If you use RowIndex alone (omit ColumnIndex), RowIndex specifies the index of the cell you work with. Cells are numbered from left-to-right and top-to-bottom.
      • If you use RowIndex and ColumnIndex, RowIndex specifies the row number of the cell you work with.
    • Required/Optional: Required.
    • Data type: Variant.
    • Values: You usually specify RowIndex as a value.
  2. Parameter: ColumnIndex.
    • Description: Column number or letter of the cell you work with.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values: You usually specify ColumnIndex as a value (column number) or letter within quotations (“”).

How to use Worksheet.Cells and Range.Item to Insert Rows

When you insert a row, use the Worksheet.Cells and Range.Item properties to return a cell. This allows you to use a specific cell as reference for the row insertion operation.

Use the Range.Offset property to return a Range object a specific number of rows above or below the cell. Use the Range.EntireRow property to return a Range object representing the entire row above which to insert the row. Please refer to the sections about the Offset and EntireRow properties below.

To insert a row above the cell specified by Worksheet.Cells, use a statement with the following structure:

Worksheet.Cells(RowIndex, ColumnIndex).EntireRow.Insert Shift:=xlShiftDown

To insert a row a specific number of rows above or below the cell specified by Worksheet.Cells, use a statement with the following structure:

Worksheet.Cells(RowIndex, ColumnIndex).Offset(RowOffset).EntireRow.Insert Shift:=xlShiftDown

Specify a Cell Range a Specific Number of Rows Below or Above a Cell or Cell Range with the Range.Offset Property

Purpose of Range.Offset

Use the Range.Offset property to return a Range object representing a cell range located a number of rows or columns away from the range the property works with.

Syntax of Range.Offset

expression.Offset(RowOffset, ColumnOffset)

“expression” is a Range object. Therefore, I simplify as follows:

Range.Offset(RowOffset, ColumnOffset)

Parameters of Range.Offset

  1. Parameter: RowOffset.
    • Description: Number of rows by which cell or cell range is offset.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values:
      • Positive number: Moves down the worksheet.
      • Negative number: Moves up the worksheet.
      • 0: Stays on the same row.
    • Default: 0. Stays on the same row.
  2. Parameter: ColumnOffset.
    • Description: Number of columns by which cell or cell range is offset.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values:
      • Positive number: Moves towards the right of the worksheet.
      • Negative number: Moves towards the left of the worksheet.
      • 0: Stays on the same column.
    • Default: 0. Stays on the same column.
    • Usage notes: When you insert a row, you can usually omit the ColumnOffset parameter. You’re generally interested in moving a number of rows (not columns) above or below.

How to Use Range.Offset to Insert Rows

When you insert a row, use the Range.Offset property to specify a cell or cell range located a specific number of rows below above another cell or cell range. This allows you to use this new cell or cell range as reference for the row insertion operation.

Use properties such as Application.ActiveCell, Worksheet.Range and Worksheet.Cells to specify the base range the Offset property works with. Please refer to the sections about the ActiveCell, Range and Cells properties above.

Specify Entire Row with the Range.EntireRow Property

Purpose of Range.EntireRow

Use the Range.EntireRow property to return a Range object representing the entire row or rows containing the cell range the property works with.

Range.EntireRow is read-only.

Syntax of Range.EntireRow

expression.EntireRow

“expression” is a Range object. Therefore, I simplify as follows:

Range.EntireRow

How to Use Range.EntireRow to Insert Rows

When you insert a row, use the Range.EntireRow property to return the entire row or rows above which the new row or rows are inserted.

Use properties such as Application.ActiveCell, Worksheet.Range and Worksheet.Cells to specify the range the EntireRow property works with. Please refer to the sections about the ActiveCell, Range and Cells properties above.

Clear Row Formatting with the Range.ClearFormats Method

Purpose of Range.ClearFormats

Use the Range.ClearFormats method to clear the formatting of a cell range.

Syntax of Range.ClearFormats

expression.ClearFormats

“expression” is a Range object. Therefore, I simplify as follows:

Range.ClearFormats

How to Use Range.ClearFormats to Insert Rows

The format of the newly-inserted row is specified by the CopyOrigin parameter of the Range.Insert method. Please refer to the description of Range.Insert and CopyOrigin above.

When you insert a row, use the Range.ClearFormats method to clear the formatting of the newly-inserted rows. Use a statement with the following structure after the statement that inserts the new row (whose formatting you want to clear):

Range.ClearFormats

“Range” is a Range object representing the newly-inserted row.

Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents the newly-inserted row. Please refer to the sections about the Rows and EntireRow properties above.

Copy Rows with the Range.Copy Method

Purpose of Range.Copy

Use the Range.Copy method to copy a cell range to another cell range or the Clipboard.

Syntax of Range.Copy

expression.Copy(Destination)

“expression” is a Range object. Therefore, I simplify as follows:

Range.Copy(Destination)

Parameters of Range.Copy

  1. Parameter: Destination.
    • Description: Specifies the destination cell range to which the copied cell range is copied.
    • Required/Optional: Optional parameter.
    • Data type: Variant.
    • Values: You usually specify Destination as a Range object.
    • Default: Cell range is copied to the Clipboard.
    • Usage notes: When you insert a copied row, omit the Destination parameter to copy the row to the Clipboard.

How to Use Range.Copy to Insert Rows

Use the Range.Copy method to copy a row which you later insert.

Use a statement with the following structure before the statement that inserts the row:

Range.Copy

“Range” is a Range object representing an entire row.

Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents a row. Please refer to the sections about the Rows and EntireRow properties above.

Related VBA and Macro Tutorials

  • General VBA constructs and structures:
    • Introduction to Excel VBA constructs and structures.
    • The Excel VBA Object Model.
    • How to declare variables in Excel VBA.
    • Excel VBA data types.
  • Practical VBA applications and macro examples:
    • How to copy and paste with Excel VBA.

You can find additional VBA and Macro Tutorials in the Archives.

Example Workbooks

This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I explain below. If you want to follow and practice, you can get immediate free access to these example workbooks by clicking the button below.

Get immediate free access to the Excel VBA Insert Row workbook examples

Each worksheet within the workbook contains a single data range. Most of the entries simply state “Data”.

Excel worksheet with data

Example #1: Excel VBA Insert Row

VBA Code to Insert Row

The following macro inserts a row below row 5 of the worksheet named “Insert row”.

Sub insertRow()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    Worksheets("Insert row").Rows(6).Insert Shift:=xlShiftDown
End Sub

Worksheets.Rows.Insert Shift:=xlShiftDown

Process Followed by Macro

Identify row; Insert new row

VBA Statement Explanation

Worksheets(“Insert row”).Rows(6).Insert Shift:=xlShiftDown
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(6).
    • VBA construct: Worksheets.Rows property.
    • Description: Returns a Range object representing row 6 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #2 above.
  4. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA inserts a row below row 5 of the worksheet.

Macro inserts new row in worksheet

Example #2: Excel VBA Insert Multiple Rows

VBA Code to Insert Multiple Rows

The following macro inserts 5 rows below row 10 of the worksheet named “Insert row”.

Sub insertMultipleRows()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    Worksheets("Insert row").Rows("11:15").Insert Shift:=xlShiftDown
End Sub

Worksheets.Rows.Insert Shift:=xlShiftDown

Process Followed by Macro

Identify several rows; Insert new rows above

VBA Statement Explanation

Worksheets(“Insert row”).Rows(“11:15”).Insert Shift:=xlShiftDown
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(“11:15”).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing rows 11 to 15 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description:
      • Inserts new rows above the rows returned by item #2 above.
      • The number of inserted rows is equal to the number of rows returned by item #2 above. This is calculated as follows:
        lastRow# - firstRow# + 1
        

        In this example: 

        15 - 11 + 1 = 5
        
  4. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the rows inserted by item #3 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA inserts 5 rows below row 10 of the worksheet.

Macro inserts multiple rows

Example #3: Excel VBA Insert Row with Same Format as Row Above

VBA Code to Insert Row with Same Format as Row Above

The following macro (i) inserts a row below row 20, and (ii) applies the formatting of row 20 to the newly-inserted row.

Sub insertRowFormatFromAbove()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    Worksheets("Insert row").Rows(21).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub

Worksheets.Rows.Insert Shift:=xlShiftDown CopyOrigin:=xlFormatFromLeftOrAbove

Process Followed by Macro

Identify row; Insert row and use formatting from above

VBA Statement Explanation

Worksheets(“Insert row”).Rows(21).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(21).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing row 21 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #2 above.
  4. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
  5. Item: CopyOrigin:=xlFormatFromLeftOrAbove.
    • VBA construct: CopyOrigin parameter of Range.Insert method.
    • Description:
      • Sets formatting of row inserted by item #3 above to be equal to that of row above (xlFormatFromLeftOrAbove).
      • You can usually omit this parameter. xlFormatFromLeftOrAbove (or 0) is the default value of CopyOrigin.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA (i) inserts a row below row 20, and (ii) applies the formatting of row 20 to the newly-inserted row.

Macro inserts row with formatting from above

Example #4: Excel VBA Insert Row with Same Format as Row Below

VBA Code to Insert Row with Same Format as Row Below

The following macro (i) inserts a row below row 25, and (ii) applies the formatting of the row below to the newly-inserted row.

Sub insertRowFormatFromBelow()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    Worksheets("Insert row").Rows(26).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
End Sub

Worksheets.Rows.Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow

Process Followed by Macro

Identify row; Insert row and use formatting from row below

VBA Statement Explanation

Worksheets(“Insert row”).Rows(26).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(26).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing row 26 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #2 above.
  4. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
  5. Item: CopyOrigin:=xlFormatFromRightOrBelow.
    • VBA construct: CopyOrigin parameter of Range.Insert method.
    • Description: Sets formatting of row inserted by item #3 above to be equal to that of row below (xlFormatFromRightOrBelow).

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA (i) inserts a row below row 25, and (ii) applies the formatting of the row below to the newly-inserted row.

Macro inserts row with formatting from below

Example #5: Excel VBA Insert Row without Formatting

VBA Code to Insert Row without Formatting

The following macro inserts a row below row 30 without applying the formatting from the rows above or below the newly- inserted row.

Sub insertRowWithoutFormat()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    Dim myNewRowNumber As Long
    myNewRowNumber = 31
    With Worksheets("Insert row")
        .Rows(myNewRowNumber).Insert Shift:=xlShiftDown
        .Rows(myNewRowNumber).ClearFormats
    End With
End Sub

Rows.Insert | Rows.ClearFormats

Process Followed by Macro

Identify row; Insert row; Clear formatting

VBA Statement Explanation

Lines #4 and #5: Dim myNewRowNumber As Long | myNewRowNumber = 31
  1. Item: Dim myNewRowNumber As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (myNewRowNumber) as of the Long data type.
      • myNewRowNumber represents the number of the newly inserted row.
  2. Item: myNewRowNumber = 31.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 31 to myNewRowNumber
Lines #6 and #9: With Worksheets(“Insert row”) | End With
  1. Item: With | End With.
    • VBA construct: With… End With statement.
    • Description: Statements within the With… End With statement (lines #7 and #8 below) are executed on the worksheet returned by item #2 below.
  2. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
Line #7: .Rows(myNewRowNumber).Insert Shift:=xlShiftDown
  1. Item: Rows(myNewRowNumber).
    • VBA construct: Worksheet.Rows property.
    • Description:
      • Returns a Range object representing a row (whose number is represented by myNewRowNumber) of the worksheet in the opening statement of the With… End With statement (line #6 above).
      • In this example, myNewRowNumber equals 31. Therefore, Worksheet.Rows returns row 31 prior to the insertion of the new row. This is a different row from that returned by Worksheet.Rows in line #8 below.
      • This line #7 returns a row prior to the row insertion. This line is that above which the new row is inserted.
      • Line #8 below returns a row after the row insertion. This line is the newly-inserted row.
  2. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #1 above.
  3. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Line #8: .Rows(myNewRowNumber).ClearFormats
  1. Item: Rows(myNewRowNumber).
    • VBA construct: Worksheet.Rows property.
    • Description:
      • Returns a Range object representing a row (whose number is represented by myNewRowNumber) of the worksheet in the opening statement of the With… End With statement (line #6 above).
      • In this example, myNewRowNumber equals 31. Therefore, Worksheet.Rows returns row 31 after the insertion of the new row. This is a different row from that returned by Worksheet.Rows in line #7 above.
      • This line #8 returns a row after the row insertion. This line is the newly-inserted row.
      • Line #7 above returns a row prior to the row insertion. This line is that below the newly-inserted row.
  2. Item: ClearFormats.
    • VBA construct: Range.ClearFormats method.
    • Description: Clears the formatting of the row returned by item #1 above.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA inserts a row below row 30 without applying the formatting from the rows above or below the newly- inserted row.

Macro inserts row without formatting

Example #6: Excel VBA Insert Row Below Active Cell

VBA Code to Insert Row Below Active Cell

The following macro inserts a row below the active cell.

Sub insertRowBelowActiveCell()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown
End Sub

ActiveCell.Offset.EntireRow.Insert Shift:=xlShiftDown

Process Followed by Macro

Identify active cell; Move 1 row down; Identify row; Insert row

VBA Statement Explanation

ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown
  1. Item: ActiveCell.
    • VBA construct: Application.ActiveCell property.
    • Description: Returns a Range object representing the active cell.
  2. Item: Offset(1).
    • VBA construct: Range.Offset property.
    • Description:
      • Returns a Range object representing the cell range 1 row below the cell returned by item #1 above.
      • In this example, Range.Offset returns the cell immediately below the active cell.
  3. Item: EntireRow:
    • VBA construct: Range.EntireRow property.
    • Description: Returns a Range object representing the entire row containing the cell range returned by item #2 above.
  4. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #3 above.
  5. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #4 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. When I execute the macro, the active cell is B35. As expected, inserts a row below the active cell.

Macro inserts row below active cell

Example #7: Excel VBA Insert Copied Row

VBA Code to Insert Copied Row

The following macro (i) copies row 45, and (ii) inserts the copied row below row 40.

Sub insertCopiedRow()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    With Worksheets("Insert row")
        .Rows(45).Copy
        .Rows(41).Insert Shift:=xlShiftDown
    End With
    Application.CutCopyMode = False
End Sub

Rows.Copy | Rows.Insert | CutCopyMode = False

Process Followed by Macro

Identify row | Copy | Identify row | Insert copied row | Cancel Cut or Copy mode

VBA Statement Explanation

Lines #4 and #7: With Worksheets(“Insert row”) | End With
  1. Item: With | End With.
    • VBA construct: With… End With statement.
    • Description: Statements within the With… End With statement (lines #5 and #6 below) are executed on the worksheet returned by item #2 below.
  2. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
Line #5: .Rows(45).Copy
  1. Item: Rows(45).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing row 45 of the worksheet in the opening statement of the With… End With statement (line #4 above).
  2. Item: Copy.
    • VBA construct: Range.Copy method.
    • Description: Copies the row returned by item #1 above to the Clipboard.
Line #6: .Rows(41).Insert Shift:=xlShiftDown
  1. Item: Rows(41).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing row 41 of the worksheet in the opening statement of the With… End With statement (line #4 above).
  2. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description:
      • Inserts a new row above the row returned by item #1 above.
      • The newly-inserted row isn’t blank. VBA inserts the row copied by line #5 above.
  3. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Line #8: Application.CutCopyMode = False
  1. Item: Application.CutCopyMode = False.
    • VBA construct: Application.CutCopyMode property.
    • Description: Cancels (False) the Cut or Copy mode and removes the moving border that accompanies this mode.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA (i) copies row 45, and (ii) inserts the copied row below row 40.

Macro inserts copied row

Example #8: Excel VBA Insert Blank Rows Between Rows in a Data Range

VBA Code to Insert Blank Rows Between Rows in a Data Range

The following macro inserts blank rows within the specified data range. This results in all rows within the data range being separated by a blank row.

Sub insertBlankRowsBetweenRows()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    Dim myFirstRow As Long
    Dim myLastRow As Long
    Dim myWorksheet As Worksheet
    Dim iCounter As Long
    myFirstRow = 5
    Set myWorksheet = Worksheets("Insert blank rows")
    myLastRow = myWorksheet.Cells.Find( _
                                        What:="*", _
                                        LookIn:=xlFormulas, _
                                        LookAt:=xlPart, _
                                        SearchOrder:=xlByRows, _
                                        SearchDirection:=xlPrevious).Row
    For iCounter = myLastRow To (myFirstRow + 1) Step -1
        myWorksheet.Rows(iCounter).Insert Shift:=xlShiftDown
    Next iCounter
End Sub

For iCounter myLastRow to myFirstRow + 1 Step -1 | Rows.Insert

Process Followed by Macro

Identify range; go to last row; Insert row; go to previous row; loop

VBA Statement Explanation

Lines #4 through #9: Dim myFirstRow As Long | Dim myLastRow As Long | Dim myWorksheet As Worksheet | Dim iCounter As Long | myFirstRow = 5 | Set myWorksheet = Worksheets(“Insert blank rows”)
  1. Item: Dim myFirstRow As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (myFirstRow) as of the Long data type.
      • myFirstRow represents the number of the first row with data in the data range you work with.
  2. Item: Dim myLastRow As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (myLastRow) as of the Long data type.
      • myLastRow represents the number of the last row with data in the data range you work with.
  3. Item: Dim myWorksheet As Worksheet.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new object variable (myWorksheet) to reference a Worksheet object.
      • myWorksheet represents the worksheet you work with.
  4. Item: Dim iCounter As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (iCounter) as of the Long data type.
      • iCounter represents a loop counter.
  5. Item: myFirstRow = 5.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 5 to myFirstRow.
  6. Item: Set myWorksheet = Worksheets(“Insert blank rows”).
    • VBA constructs:
      • Set statement.
      • Workbooks.Worksheets property.
    • Description: Assigns the Worksheet object representing the “Insert blank rows” worksheet to myWorksheet.
Lines #10 through #15: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
  1. Item: myLastRow =.
    • VBA construct: Assignment statement.
    • Description: Assigns the value returned by items #2 through #9 below to myLastRow.
  2. Item: myWorksheet.Cells.
    • VBA construct: Worksheet.Cells property.
    • Description: Returns a Range object representing all cells on myWorksheet.
  3. Item: Find.
    • VBA construct: Range.Find method.
    • Description:
      • Finds information in the cell range returned by item #2 above and returns a Range object representing the first cell where the information is found.
      • In this example, the Range object Range.Find returns represents the last cell with data in last row with data in myWorksheet.
  4. Item: What:=”*”.
    • VBA construct: What parameter of Range.Find method.
    • Description: Specifies the data Range.Find searches for. The asterisk (*) is a wildcard and, therefore, Range.Find searches for any character sequence.
  5. Item: LookIn:=xlFormulas.
    • VBA construct: LookIn parameter of Range.Find method.
    • Description: Specifies that Range.Find looks in formulas (xlFormulas).
  6. Item: LookAt:=xlPart.
    • VBA construct: LookAt parameter of Range.Find method.
    • Description: Specifies that Range.Find looks at (and matches) a part (xlPart) of the search data.
  7. Item: SearchOrder:=xlByRows.
    • VBA construct: SearchOrder parameter of Range.Find method.
    • Description: Specifies that Range.Find searches by rows (xlByRows).
  8. Item: SearchDirection:=xlPrevious.
    • VBA construct: SearchDirection parameter of Range.Find method.
    • Description: Specifies that Range.Find searches for the previous match (xlPrevious).
  9. Item: Row.
    • VBA construct: Range.Row property.
    • Description:
      • Returns the row number of the Range object returned by item #3 above.
      • In this example, the number returned by Range.Row corresponds to the last row with data in myWorksheet.
Lines #16 and #18: For iCounter = myLastRow To (myFirstRow + 1) Step -1 | Next iCounter
  1. Item: For | Next iCounter.
    • VBA construct: For… Next statement.
    • Description:
      • Repeats the statement inside the For… Next loop (line #17 below) a specific number of times.
      • In this example:
        • The macro starts on the last row of the data range as specified by item #2 below.
        • Every iteration, the loop counter decreases by 1, as specified by item #4 below. Therefore, the macro moves to the previous row.
        • The macro exits the loop after working with the second row in the data range (myFirstRow + 1), as specified by item #3 below.
  2. Item: iCounter = myLastRow.
    • VBA construct: Counter and Start of For… Next statement.
    • Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
  3. Item: To (myFirstRow + 1).
    • VBA construct: End of For… Next statement.
    • Description: Specifies the value represented by myFirstRow plus 1 (myFirstRow + 1) as the final value of the loop counter.
  4. Item: Step -1.
    • VBA construct: Step of For… Next statement.
    • Description: Specifies that the loop counter (iCounter) decreases by 1 (-1) every loop iteration.
Line #17: myWorksheet.Rows(iCounter).Insert Shift:=xlShiftDown
  1. Item: myWorksheet.Rows(iCounter).
    • VBA construct: Worksheet.Rows property.
    • Description:
      • Returns a Range object representing the row (whose number is represented by iCounter) of myWorksheet.
      • Worksheet.Rows returns the row through which the macro is currently looping.
  2. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description:
      • Inserts a new row above the row returned by item #1 above.
      • The macro loops through each line in the data range (excluding the first) as specified by lines #16 and #18 above. Therefore, Range.Insert inserts a row between all rows with data.
  3. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA inserts blank rows within the specified data range. This results in all rows within the data range being separated by a blank row.

Macro inserts blank rows between rows

Example #9: Excel VBA Insert a Number of Rows Every Number of Rows in a Data Range

VBA Code to Insert a Number of Rows Every Number of Rows in a Data Range

The following macro inserts 2 rows every 3 rows within the specified data range.

Sub insertMRowsEveryNRows()
    'Source: powerspreadsheets.com/
    'For further information: https://powerspreadsheets.com/excel-vba-insert-row/
    Dim myFirstRow As Long
    Dim myLastRow As Long
    Dim myNRows As Long
    Dim myRowsToInsert As Long
    Dim myWorksheet As Worksheet
    Dim iCounter As Long
    myFirstRow = 5
    myNRows = 3
    myRowsToInsert = 2
    Set myWorksheet = Worksheets("Insert M rows every N rows")
    myLastRow = myWorksheet.Cells.Find( _
                                        What:="*", _
                                        LookIn:=xlFormulas, _
                                        LookAt:=xlPart, _
                                        SearchOrder:=xlByRows, _
                                        SearchDirection:=xlPrevious).Row
    For iCounter = myLastRow To (myFirstRow + myNRows) Step -1
        If (iCounter - myFirstRow) Mod myNRows = 0 Then myWorksheet.Rows(iCounter & ":" & iCounter + myRowsToInsert - 1).Insert Shift:=xlShiftDown
    Next iCounter
End Sub

For iCounter = myLastRow To myFirstRow + myNRows Step -1 | If multiple of myNRows Then Rows.Insert

Process Followed by Macro

Identify data range; go to last row; conditional test; insert row; loop

VBA Statement Explanation

Lines #4 through 13: Dim myFirstRow As Long | Dim myLastRow As Long | Dim myNRows As Long | Dim myRowsToInsert As Long | Dim myWorksheet As Worksheet | Dim iCounter As Long | myFirstRow = 5 | myNRows = 3 | myRowsToInsert = 2 | Set myWorksheet = Worksheets(“Insert M rows every N rows”)
  1. Item: Dim myFirstRow As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (myFirstRow) as of the Long data type.
      • myFirstRow represents the number of the first row with data in the data range you work with.
  2. Item: Dim myLastRow As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (myLastRow) as of the Long data type.
      • myLastRow represents the number of the last row with data in the data range you work with.
  3. Item: Dim myNRows As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (myNRows) as of the Long data type.
      • myNRows represents the number of rows per block. The macro doesn’t insert rows between these rows.
  4. Item: Dim myRowsToInsert As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (myRowsToInsert) as of the Long data type.
      • myRowsToInsert represents the number of rows to insert.
  5. Item: Dim myWorksheet As Worksheet.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new object variable (myWorksheet) to reference a Worksheet object.
      • myWorksheet represents the worksheet you work with.
  6. Item: Dim iCounter As Long.
    • VBA construct: Dim statement.
    • Description:
      • Declares a new variable (iCounter) as of the Long data type.
      • iCounter represents a loop counter.
  7. Item: myFirstRow = 5.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 5 to myFirstRow.
  8. Item: myNRows = 3.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 3 to myNRows.
  9. Item: myRowsToInsert = 2.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 2 to myRowsToInsert.
  10. Item: Set myWorksheet = Worksheets(“Insert M rows every N rows”).
    • VBA constructs:
      • Set statement.
      • Workbooks.Worksheets property.
    • Description: Assigns the Worksheet object representing the “Insert M rows every N rows” worksheet to myWorksheet.
Lines #14 through #19: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
  1. Item: myLastRow =.
    • VBA construct: Assignment statement.
    • Description: Assigns the value returned by items #2 through #9 below to myLastRow.
  2. Item: myWorksheet.Cells.
    • VBA construct: Worksheet.Cells property.
    • Description: Returns a Range object representing all cells on myWorksheet.
  3. Item: Find.
    • VBA construct: Range.Find method.
    • Description:
      • Finds information in the cell range returned by item #2 above and returns a Range object representing the first cell where the information is found.
      • In this example, the Range object Range.Find returns represents the last cell with data in last row with data in myWorksheet.
  4. Item: What:=”*”.
    • VBA construct: What parameter of Range.Find method.
    • Description: Specifies the data Range.Find searches for. The asterisk (*) is a wildcard and, therefore, Range.Find searches for any character sequence.
  5. Item: LookIn:=xlFormulas.
    • VBA construct: LookIn parameter of Range.Find method.
    • Description: Specifies that Range.Find looks in formulas (xlFormulas).
  6. Item: LookAt:=xlPart.
    • VBA construct: LookAt parameter of Range.Find method.
    • Description: Specifies that Range.Find looks at (and matches) a part (xlPart) of the search data.
  7. Item: SearchOrder:=xlByRows.
    • VBA construct: SearchOrder parameter of Range.Find method.
    • Description: Specifies that Range.Find searches by rows (xlByRows).
  8. Item: SearchDirection:=xlPrevious.
    • VBA construct: SearchDirection parameter of Range.Find method.
    • Description: Specifies that Range.Find searches for the previous match (xlPrevious).
  9. Item: Row.
    • VBA construct: Range.Row property.
    • Description:
      • Returns the row number of the Range object returned by item #3 above.
      • In this example, the number returned by Range.Row corresponds to the last row with data in myWorksheet.
Lines #20 and #22: For iCounter = myLastRow To (myFirstRow + myNRows) Step -1 | Next iCounter
  1. Item: For | Next iCounter.
    • VBA construct: For… Next statement.
    • Description:
      • Repeats the statement inside the For… Next loop (line #21 below) a specific number of times.
      • In this example:
        • The macro starts on the last row of the data range as specified by item #2 below.
        • Every iteration, the loop counter decreases by 1, as specified by item #4 below. Therefore, the macro moves to the previous row.
        • The macro exits the loop after working with the row below the first block of rows you want to keep, as specified by item #3 below. Each block of rows has a number of rows equal to myNRows.
        • In this example, myNRows equals 3. Therefore, the macro exits the loop after working with the fourth row in the data range.
  2. Item: iCounter = myLastRow.
    • VBA constructs: Counter and Start of For… Next statement.
    • Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
  3. Item: To (myFirstRow + myNRows).
    • VBA construct: End of For… Next statement.
    • Description: Specifies the value represented by myFirstRow plus myNRows (myFirstRow + myNRows) as the final value of the loop counter.
  4. Item: Step -1.
    • VBA construct: Step of For… Next statement.
    • Description: Specifies that the loop counter (iCounter) decreases by 1 (-1) every loop iteration.
Line #21: If (iCounter – myFirstRow) Mod myNRows = 0 Then myWorksheet.Rows(iCounter & “:” & iCounter + myRowsToInsert – 1).Insert Shift:=xlShiftDown
  1. Item: If | Then.
    • VBA construct: If… Then… Else statement.
    • Description: Conditionally executes the statement specified by items #3 and #4 below, subject to condition specified by item #2 below being met.
  2. Item: (iCounter – myFirstRow) Mod myNRows = 0.
    • VBA constructs:
      • Condition of If… Then… Else statement.
      • Numeric expression with Mod operator.
    • Description:
      • The Mod operator (Mod) (i) divides one number (iCounter – myFirstRow) by a second number (myNRows), and (ii) returns the remainder of the division.
      • The condition ((iCounter – myFirstRow) Mod myNRows = 0) is met (returns True) if the remainder returned by Mod is 0.
      • The condition is met (returns True) every time the macro loops through a row above which blank rows should be added.
        • iCounter represents the number of the row through which the macro is currently looping.
        • (iCounter – myFirstRow) is the number of rows (in the data range) above the row through which the macro is currently looping.
        • ((iCounter – myFirstRow) Mod myNRows) equals 0 when the number of rows returned by (iCounter – myFirstRow) is a multiple of myNRows. This ensures that the number of rows left above the row through which the macro is currently looping can be appropriately separated into blocks of myNRows. In this example, myNRows equals 3. Therefore, the condition is met every 3 rows.
  3. Item: myWorksheet.Rows(iCounter & “:” & iCounter + myRowsToInsert – 1).
    • VBA constructs:
      • Statements executed if the condition specified by item #2 above is met.
      • Worksheet.Rows property.
    • Description:
      • Returns an object representing several rows of myWorksheet. The first row is represented by iCounter. The last row is represented by (iCounter + myRowsToInsert – 1).
      • The number of rows Worksheet.Rows returns equals the number of rows to insert (myRowsToInsert).
        • iCounter represents the number of the row through which the macro is currently looping.
        • (iCounter + myRowsToInsert – 1) returns a row located a number of rows (myRowsToInsert – 1) below the row through which the macro is currently looping. In this example, myRowsToInsert equals 2. Therefore, (iCounter + myRowsToInsert – 1) returns a row located 1 (2 – 1) rows below the row through which the macro is currently looping.
  4. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description:
      • Inserts new rows above the rows returned by item #3 above.
      • The number of inserted rows is equal to the value of myRowsToInsert. This is calculated as follows:
        lastRow# - firstRow# + 1
        (iCounter + myRowsToInsert - 1) - iCounter + 1 = myRowsToInsert
        

        In this example, if the current value of iCounter is 8: 

        (8 + 2 - 1) - 8 + 1
        9 - 8 + 1 = 2
        
  5. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the rows inserted by item #4 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA inserts 2 rows every 3 rows within the specified data range.

Macro inserts rows every number of rows

Это продолжение перевода книги Зак Барресс и Кевин Джонс. Таблицы Excel: Полное руководство для создания, использования и автоматизации списков и таблиц (Excel Tables: A Complete Guide for Creating, Using and Automating Lists and Tables by Zack Barresse and Kevin Jones. Published by: Holy Macro! Books. First printing: July 2014. – 161 p.). Visual Basic for Applications (VBA) – это язык программирования, который можно использовать для расширения стандартных возможностей Excel. VBA позволяет автоматизировать сложные или повторяющиеся задачи. Например, VBA можно использовать для форматирования листа, получаемого ежедневно из внешнего источника, извлечения данных с веб-страницы раз в неделю или построения сложной пользовательской функции листа.

Предыдущая глава        Содержание    Следующая глава

Ris. 9.1. Redaktirovanie makrosov

Рис. 9.1. Редактирование макросов

Скачать заметку в формате Word или pdf

Вот некоторые примеры автоматизации Таблиц Excel:

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

Для работы с этой главой лучше всего, если у вас есть начальный уровень программирования, вы знакомы с объектной моделью и хотите расширить функциональность Таблиц Excel (см. Джон Уокенбах. Excel 2010. Профессиональное программирование на VBA). Среда VBA не русифицирована.

Один из самых простых способов начать работать с VBA – это использовать запись макросов. При этом действия, которые вы совершаете в Excel, записываются в среде VBA в виде инструкций. Не забудьте выключить запись макросов, когда автоматизированные действия будут завершены. Вы можете просматривать и редактировать код VBA, пройдя по меню Разработчик –> Макросы, выбрать имя макроса и нажать кнопку Изменить (рис. 9.1). Код, сгенерированный при записи макросов, не самый эффективный, и вы часто можете улучшить его с помощью редактирования.

Если вкладка Разработчик не видна, включите ее, пройдя по меню Файл –> Параметры –> Настроить ленту, и установив флажок на вкладке Разработчик.

VBA, Excel и объекты

Этот раздел можно пропустить, если у вас уже есть опыт работы с объектами в среде Excel VBA.

В среде VBA приложение Excel представляет объекты, к которым можно получить доступ, в виде объектной модели Excel. Основные объекты Excel:

  • Application – Приложение Excel.
  • Workbooks – коллекция всех книг, открытых в данный момент в приложении Excel. В общем случае коллекция – набор объектов. В этом случае коллекция Workbooks представляет собой набор отдельных объектов Workbook.
  • Workbook – одна книга.
  • Worksheets – коллекция всех листов в рабочей книге.
  • Worksheet – отдельный рабочий лист или вкладка в рабочей книге.
  • Cells – совокупность всех ячеек на листе.
  • Range – набор из одной или нескольких ячеек на одном листе. Клетки могут быть прерывистыми. Любая ссылка даже на одну ячейку является объектом Range.

Объекты имеют свойства. Каждый объект принадлежит родительскому объекту. Например, родителем объекта Workbook является объект Application, а родителем объекта Cell – объект Worksheet. Одним из исключений является объект Application, который не имеет родителя; это объект самого высокого уровня, доступный при просмотре объектной модели Excel. При описании контекста объекта или метода часто используются следующие термины:

  • Parent – родительский объект. Например, родительский объект для Cell – это Worksheet.
  • Member – член родительского объекта. Например, член объекта Worksheet – объект Cell. Член также может быть методом, который выполняет действие.

Когда вы ссылаетесь на объект, вы должны начать с самого высокого уровня. Чтобы найти каждый подчиненный объект, введите родительский объект, за которым следует точка, а затем дочерний элемент. Например, чтобы сослаться на значение ячейки A1 на листе Sheet1 в книге My Workbook.xlsx, используйте следующий синтаксис:

Application.Workbooks(«My Workbook.xlsm»).Worksheets(«Sheet1»).Cells(1,1).Value

Ссылки в VBA как правило используют синтаксис R1C1, а не А1.

Объектная модель Excel предоставляет объекты по умолчанию в зависимости от того, какой элемент приложения в данный момент активен. Например, следующий синтаксис ссылается на ячейку A1 на листе, активном в момент выполнения кода:

Хотя этот синтаксис работает, он не считается хорошей практикой. Мы рекомендуем использовать объект ActiveSheet, если вы действительно намеревались ссылаться на активный лист:

Application.ActiveSheet.Cells(1,1).Value

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

Workbooks(«My Workbook.xlsm»).Worksheets(«Sheet1»).Cells(1,1).Value

ActiveSheet.Cells(1,1).Value

Вы можете назначить ссылку на любой объект переменной, если эта переменная имеет тот же тип, что и объект, или определена как универсальный тип объекта. Основная причина для этого – удобство. Если вы ссылаетесь на объект повторно, то выделение переменной для ссылки на этот объект может привести к уменьшению объема кода, который будет легче читать и поддерживать. Например, вы можете назначить ссылку на Sheet1 переменной:

Dim TargetWorksheet As Worksheet

Set TargetWorksheet = Workbooks(«My Workbook.xlsm»).Worksheets(«Sheet1»)

Теперь ссылка на А1 может быть записана в виде:

TargetWorksheet.Cells(1,1).Value

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

Следует различать объекты, экземпляры объектов и ссылки на объекты. Объект включает в себя объектную модель (свойства и методы, которые ему принадлежат) и код, который управляет его поведением. Примером объекта является Worksheet. Экземпляр объекта является конкретным экземпляром этого объекта и включает в себя данные и значения свойств, связанные с этим экземпляром объекта. Листы Sheet1 и Sheet2 примеры экземпляров объектов. Переменная, ссылающаяся на объект, содержит ссылку на объект.

При определении переменных, ссылающихся на объекты, необходимо определить переменную того же типа, что и объект, на который ссылаются, или присвоить универсальный тип объекта. В общем случае универсальный тип объекта следует использовать только в том случае, если этой переменной будут присвоены ссылки на другие объекты различных типов; при использовании универсального типа объекта редактор VBA не может помочь вам с интеллектуальной подсказкой IntelliSense (IntelliSense представляет список свойств и методов объекта при вводе ссылки на объект, за которой следует точка.)

В дальнейшем описании мы используем следующие объекты:

  • ThisWorkbook – рабочая книга, в которой выполняется код. Это удобно, когда единственная книга, на которую ссылаются, является той, в которой находится код. С этой рабочей книгой работать легче, чем с рабочими книгами (My Workbook.xlsm), особенно когда имя рабочей книги может меняться.
  • Me – когда код находится в модуле кода листа, Me – это удобный способ ссылаться на объект листа, в котором находится код.

Excel Online открывает файлы с VBA (при просмотре в браузере), но не выполняет код. Код игнорируется при открытии книги в приложении Excel Online, но сам код сохраняется.

Объект ListObject

Excel использует объект ListObject для представления таблицы в объектной модели Excel. Он содержится в коллекции ListObjects, которая принадлежит объекту Worksheet. Используйте этот синтаксис для ссылки на Таблицу на листе:

ThisWorkbook.Worksheets(«Sheet1»).ListObjects(«Table1»)

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

Поскольку ListObjects – это набор таблиц, вы можете получить доступ к конкретной Таблице с помощью индекса:

ThisWorkbook.Worksheets(«Sheet1»).ListObjects(1)

Индекс (или позиция) объекта ListObject в коллекции ListObjects определяется порядком, в котором объекты ListObject были созданы на листе. Объект ListObject может быть назначен переменной, которая была определена как тип ListObject. Объект ListObject имеет ряд свойств и методов, используемых для доступа к таблицам и управления ими.

Свойства объекта Таблица

Пять свойств представляют собой основные части таблицы. Каждое из этих свойств является объектом диапазона Range. Два дополнительных свойства или коллекции предоставляют доступ к строкам и столбцам Таблицы. Каждая коллекция предоставляет доступ ко всем объектам ListRow и ListColumn в Таблице.

Свойство Range

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

Свойство HeaderRowRange

Свойство HeaderRowRange возвращает строку заголовка таблицы. Тип объекта – Range. Свойство не может быть установлено. Диапазон всегда представляет собой одну строку – строку заголовка – и распространяется на все столбцы таблицы. Если строка заголовка отключена, этому свойству присваивается значение Nothing.

Свойство DataBodyRange

Свойство DataBodyRange возвращает тело таблицы. Тип объекта – Range. Свойство не может быть установлено. Диапазон – это каждая строка между заголовком и общей строкой и распространяется на все столбцы таблицы. Если таблица не содержит строк, свойство DataBodyRange не возвращает Nothing (и ListRows.Count возвращает 0). Это единственный случай, когда свойство InsertRowRange возвращает объект диапазона, который можно использовать для вставки новой строки. В этом состоянии таблица выглядит как одна строка без каких-либо значений. Как только одна ячейка в таблице получает значение, InsertRowRange получает значение Nothing, а DataBodyRange – значение строк данных в таблице.

Свойство TotalRowRange

Свойство TotalRowRange возвращает итоговую строку Таблицы. Тип объекта – Range. Свойство не может быть установлено. Диапазон всегда представляет собой одну строку – строку итогов – и распространяется на все столбцы Таблицы. Если строка итогов отключена, это свойство имеет значение Nothing.

Свойство InsertRowRange

Свойство InsertRowRange возвращает текущую строку вставки Таблицы. Тип объекта – Range. Свойство не может быть установлено. В Excel 2007 и более поздних версиях InsertRowRange возвращает только первую строку данных и только тогда, когда таблица не содержит никаких данных. В противном случае он ничего не возвращает и фактически бесполезен.

Свойство ListRows

Свойство ListRows возвращает коллекцию всех строк в таблице DataBodyRange. Это тип объекта ListRows, который ведет себя очень похоже на объект Collection и содержит коллекцию объектов ListRow. Свойство не может быть установлено. На строки ссылаются по индексу, отсчитываемому от единицы (one-based index).[1] В пустой таблице нет строк. Метод Add объекта ListRows используется для вставки одной новой строки за один раз.

Свойство ListColumns

Свойство ListColumns возвращает коллекцию всех столбцов таблицы. Это тип объекта ListColumns, который ведет себя очень похоже на объект Collection и содержит коллекцию объектов ListColumn. Свойство не может быть установлено. На столбцы ссылается one-based. Таблица всегда содержит хотя бы один столбец.

Свойства структуры Таблиц

Таких свойств несколько. Все они являются членами объекта ListObject.

Свойство ShowAutoFilter возвращает или задает, включен ли Автофильтр. Свойство имеет логический тип. Если значение True, Автофильтр включен, False – отключен. Свойство представлено в пользовательском интерфейсе Excel, меню Данные –> Сортировка и фильтр –> Фильтр.

Свойство ShowAutoFilterDropDown возвращает или задает значение, указывающее отображается ли кнопка ниспадающего списка Автофильтра. Свойство имеет логический тип. Если значение True, кнопка отражается, False – не отражается. Если ShowAutoFilter имеет значение False, то свойство ShowAutoFilterDropDown изменить нельзя. Свойство представлено в пользовательском интерфейсе Excel, меню Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Кнопка фильтра.

Свойство ShowHeaders возвращает или задает, включена ли строка заголовка таблицы. Свойство имеет логический тип. Если значение True, строка заголовка таблицы включена, False – отключена. Свойство представлено в пользовательском интерфейсе Excel, меню Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Строка заголовков.

Свойство ShowTotals возвращает или задает включена ли строка итогов. Свойство имеет логический тип. Если значение True, строка итогов включена, False – отключена. Свойство представлено в пользовательском интерфейсе Excel, меню Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Строка итогов.

Свойства стилей Таблиц

Этих свойств также несколько. Все они являются членами объекта ListObject.

Свойство TableStyle возвращает или задает имя стиля таблицы. Свойство имеет тип Variant. Чтобы изменить стиль таблицы, необходимо задать имя нужного стиля. При назначении стиля таблицы к таблице применяются только элементы стиля, определенные в этом стиле (подробнее см. Глава 7. Форматирование Таблиц Excel). Чтобы определить имя стиля, наведите курсор мыши на нужный стиль в галерее стилей таблиц, пока Excel не отобразит имя этого стиля:

Ris. 9.2. Opredelenie imeni stilya tablitsy

Рис. 9.2. Определение имени стиля таблицы

Чтобы присвоить это имя свойству TableStyle, используйте код:

ActiveSheet.ListObjects(«qryCrosstab2»).TableStyle = «TableStyleLight21»

Здесь qryCrosstab2 – имя Таблицы. Внутренние имена всех встроенных стилей не содержат пробелов и английские, хотя имена, отображаемые на ленте, содержат пробелы и русифицированы. Чтобы узнать имя таблицы, которое нужно использовать в коде VBA, запустите запись макроса, присвойте стиль, завершите запись макроса, и посмотрите его код.

Свойство TableStyle представлено в пользовательском интерфейсе Excel в виде массива кнопок в группе Работа с таблицами –> Конструктор –> Стили таблиц.

Свойство ShowTableStyleColumnStripes возвращает или задает, форматируются ли нечетные столбцы таблицы иначе, чем четные столбцы. Свойство имеет логический тип. Если значение True, нечетные столбцы таблицы форматируются иначе, чем четные столбцы, как определено в заданном стиле таблицы. Нечетные столбцы форматируются с использованием параметров полосы первого столбца стиля таблицы, а четные строки форматируются с использованием параметров полосы второго столбца стиля таблицы. Если ShowTableStyleColumnStripes имеет значение False, столбцы таблицы не форматируются с использованием назначенного стиля таблицы. Свойство ShowTableStyleColumnStripes представлено в пользовательском интерфейсе Excel в виде флажка на ленте Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Чередующиеся столбцы.

Обратите внимание, что по умолчанию количество столбцов в каждой полосе равно одному, но вы можете изменить его на большее число для элементов полосы первого столбца и полосы второго столбца независимо. Дополнительную информацию смотрите в главе 7.

Свойство ShowTableStyleRowStripes возвращает или задает, форматируются ли нечетные строки таблицы иначе, чем четные строки. Свойство имеет логический тип. Если значение True, нечетные строки таблицы форматируются иначе, чем четные строки, как определено в заданном стиле таблицы. Нечетные строки форматируются с использованием первой полосы строк стиля таблицы, а четные строки форматируются с использованием второй полосы строк стиля таблицы. Если свойству ShowTableStyleRowStripes присвоено значение False, строки таблицы не форматируются с использованием назначенного стиля таблицы. Это свойство эквивалентно флажку на ленте Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Чередующиеся строки.

Свойство ShowTableStyleFirstColumn возвращает или задает, выделяется ли первый столбец. Свойство имеет логический тип. Если значение True, первый столбец таблицы форматируется так, как определено в настройках первого столбца назначенного стиля таблицы. Если установлено значение False, первый столбец таблицы не форматируется в соответствии с заданным стилем таблицы. Это свойство представлено в пользовательском интерфейсе Excel в виде флажка на ленте Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Первый столбец.

Свойство ShowTableStyleLastColumn возвращает или задает, выделяется ли последний столбец. Свойство имеет логический тип. Если значение True, последний столбец таблицы форматируется так, как определено в настройках последнего столбца назначенного стиля таблицы. Если установлено значение False, последний столбец таблицы не форматируется в соответствии с заданным стилем таблицы. Это свойство представлено в пользовательском интерфейсе Excel в виде флажка на ленте Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Последний столбец.

Другие свойства объекта Таблицы

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

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

Свойство AlternativeText возвращает или задает замещающий текст таблицы. Свойство имеет строковый тип. Установка этого свойства перезаписывает любое предыдущее значение. Это свойство представлено в пользовательском интерфейсе Excel в диалоговом окне Замещающий текст, доступ к которому можно получить, щелкнув правой кнопкой мыши в любом месте таблицы и пройдя по меню Таблица –> Замещающий текст. Это свойство отображается и редактируется в текстовом поле Заголовок.

Ris. 9.3. Zameshhayushhij tekst

Рис. 9.3. Замещающий текст

Свойство AutoFilter – это объект AutoFilter со своими собственными свойствами и методами. Его можно использовать для проверки настроек Автофильтра и повторного применения или очистки настроек Автофильтра в таблице. Он не используется для установки фильтров; для этого используется метод AutoFilter объекта Range.

Свойство Comment возвращает или задает комментарий таблицы. Свойство имеет строковый тип. Это свойство, добавленное в Excel 2007, представлено в пользовательском интерфейсе Excel в диалоговом окне Диспетчер имен, доступ к которому можно получить, пройдя по меню Формулы –> Определенные имена –> Диспетчер имен. Комментарий (примечание) отображается в правом столбце, и вы можете изменить его, кликнув на кнопку Изменить (рис. 9.4). Напомним, поскольку все Таблицы именуются, их имена отражаются в окне Диспетчер имен.

Ris. 9.4. Dispetcher imen

Рис. 9.4. Диспетчер имен

Свойство DisplayName возвращает или задает имя таблицы. Свойство имеет строковый тип. При назначении имени применяются те же ограничения, что и при изменении имени таблицы в пользовательском интерфейсе Excel; например, оно не может дублировать иное имя и не может содержать пробелов. Это свойство, добавленное в Excel 2007, ведет себя почти так же, как и свойство Name, но при использовании свойства DisplayName присваиваемое имя должно соответствовать ограничениям на имя таблицы, иначе возникает ошибка. Это свойство представлено в пользовательском интерфейсе Excel в виде поля ввода текста Работа с таблицами –> Конструктор –> Свойства –> Имя таблицы.

Свойство Name возвращает или задает имя таблицы. Свойство имеет строковый тип. В отличие от свойства DisplayName, когда вы присваиваете значение свойству Name, Excel изменяет имя так, чтобы оно соответствовало правилам имени таблицы. Например, он меняет пробелы на подчеркивания и, если имя уже существует, добавляет к нему символ подчеркивания, за которым следует число. Это свойство представлено в пользовательском интерфейсе Excel в виде поля ввода текста Работа с таблицами –> Конструктор –> Свойства –> Имя таблицы.

Чтобы избежать проблем, используйте свойство DisplayName вместо свойства Name для присвоения имени таблице. Свойство DisplayName создает ошибку, если имя является незаконным или уже определено в другом месте. С другой стороны, Excel будет искажать значение, присвоенное свойству Name, чтобы сделать его законным, и таким образом имя может оказаться не совсем тем, что вы намеревались.

Свойство Parent возвращает родителя таблицы. Свойство имеет тип объекта и всегда возвращает Worksheet. Свойство не может быть установлено.

Свойство QueryTable возвращает объект QueryTable, который ссылается на сервер списков. Это тип объекта QueryTable. Свойство не может быть установлено. Объект QueryTable предоставляет свойства и методы, позволяющие управлять таблицей. Следующий код публикует Таблицу на сервере SharePoint и называет опубликованный список Register. Затем он восстанавливает объект QueryTable для таблицы и устанавливает свойству MaintainConnection Таблицы значение True:

Dim Table As ListObject

Dim QueryTable As QueryTable

Dim PublishTarget(4) As String

Dim ConnectionString As String

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

PublishTarget(0) = «0»

PublishTarget(1) = «http://myserver/myproject»

PublishTarget(2) = «1»

PublishTarget(3) = «Register»

ConnectionString = Table.Publish(PublishTarget, True)

Set QueryTable = Table.QueryTable QueryTable.MaintainConnection = True

Свойство SharePointURL возвращает URL-адрес списка SharePoint. Свойство имеет строковый тип. Это свойство устанавливается при создании или обслуживании подключения к SharePoint и не может быть изменено. Это свойство представлено в пользовательском интерфейсе Excel в виде кнопки Работа с таблицами –> Конструктор –> Данные из внешней таблицы –> Экспорт –>  Экспорт таблицы в список SharePoint. Следующий код публикует существующую таблицу на сервере SharePoint с помощью SharePointURL и называет опубликованный список Register:

Dim Table As ListObject

Dim QueryTable As QueryTable

Dim PublishTarget(4) As String

Dim ConnectionString As String

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

PublishTarget(0) = «0»

PublishTarget(1) = Table.SharePointURL PublishTarget(2) = «1»

PublishTarget(3) = «Register»

ConnectionString = Table.Publish(PublishTarget, True)

Свойство Slicers возвращает коллекцию срезов, связанных с таблицей. Свойство имеет тип Slicers, который ведет себя очень похоже на объект Collection и содержит коллекцию объектов Slicer. Свойство не может быть установлено. Объект Slicers используется для добавления, управления и удаления срезов, связанных с таблицей. Каждый объект среза предоставляет свойства и методы, которые позволяют управлять срезом. Свойства срезов была добавлена в объект ListObject в Excel 2013.

В следующем примере срез добавляется и помещается на том же листе, что и Таблица. Чтобы добавить срез сначала нужно создать объект SlicerCache для каждого среза:

Dim Table As ListObject

Dim SlicerCache As SlicerCache

Dim Slicer As Slicer

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set SlicerCache = ThisWorkbook.SlicerCaches.Add(Table, «Category»)

SlicerCache.RequireManualUpdate = False

Set Slicer = SlicerCache.Slicers.Add(Table.Parent, , _

   «tblRegisterCategory», «Category», 100, 400)

Объект SlicerCache привязан к таблице и фильтруемому столбцу. Сам срез является визуальным представлением кэша среза и имеет родителя, имя, заголовок и позицию; он также имеет размер, но в приведенном выше примере используется размер по умолчанию. Свойство RequireManualUpdate объекта SlicerCache имеет значение False, чтобы избежать появления в срезе сообщения Устарело.

Следующий срез настроен на отображение категории Расходы (Expense) и скрытие категории Доходы (Income):

Dim Table As ListObject

Dim Slicer As Slicer

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set Slicer = Table.Slicers(«tblRegisterCategory»)

With Slicer.SlicerCache

   .SlicerItems(«Expense»).Selected = True

   .SlicerItems(«Income»).Selected = False

End With

Следующий срез настроен для отображения только одной категории:

Dim Table As ListObject

Dim Slicer As Slicer

Dim SlicerItem As SlicerItem

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set Slicer = Table.Slicers(«tblRegisterCategory»)

With Slicer.SlicerCache

   .ClearManualFilter

   For Each SlicerItem In .SlicerItems

      If SlicerItem.Name <> «Expense» Then

         SlicerItem.Selected = False

      End If

   Next SlicerItem

End Wit

В следующем примере происходит очистка фильтр среза:

Dim Table As ListObject

Dim Slicer As Slicer

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set Slicer = Table.Slicers(«tblRegisterCategory»)

Slicer.SlicerCache.ClearManualFilter

В следующем примере срез удаляется. Обратите внимание, что кэш среза также удаляется:

Dim Table As ListObject

Dim Slicer As Slicer

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set Slicer = Table.Slicers(«tblRegisterCategory»)

Slicer.Delete

Table.ShowAutoFilter = False

Обратите внимание, что свойство таблицы ShowAutoFilter имеет значение False, чтобы скрыть раскрывающийся список, который остается после удаления среза. Если Автофильтр таблицы был включен при создании среза, то этот шаг не требуется. Если Автофильтр таблицы не был включен до добавления среза, то после удаления среза раскрывающийся элемент управления Автофильтром остается только у столбца, для которого был удален срез.

Свойство Sort возвращает объект сортировки таблицы. Свойство имеет тип Sort object. Свойство не может быть установлено. В следующем примере Таблица сортируется по дате и описанию:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

With Table

   .Sort.SortFields.Add .ListColumns(«Date»).DataBodyRange,_

      xlSortOnValues, xlAscending

   .Sort.SortFields.Add .ListColumns(«Description»)._

      DataBodyRange, xlSortOnValues, xlAscending

   .Sort.Apply

   .Sort.SortFields.Clear

End With

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

Свойство SourceType возвращает текущий источник таблицы. Свойство имеет тип XlListObjectSourceType. Свойство не может быть установлено. Свойство может принимать следующие константы:

  • xlSrcExternal или 0 – источник является внешним источником данных, таким как сайт Microsoft SharePoint.
  • xlSrcModel или 4 – источником является модель Power Pivot.
  • xlSrcQuery или 3 – источником является запрос Power Query.
  • xlSrcRange или 1 – источником является объект Range.
  • xlSrcXml или 2 – источником является XML.

Свойство Summary возвращает или задает текст, используемый для замещающего текста при публикации таблицы. Свойство имеет строковый тип, введенный в Excel 2010. Установка этого свойства перезаписывает любое предыдущее значение. Это свойство представлено в пользовательском интерфейсе Excel в диалоговом окне Замещающий текст, доступ к которому можно получить, щелкнув правой кнопкой мыши в любом месте Таблицы и выбрав Таблица –> Замещающий текст (см. рис. 9.3). Это свойство отображается и редактируется в текстовом поле Описание.

Свойство TableObject возвращает объект TableObject Таблицы. Свойство имеет тип объекта TableObject. Свойство не может быть установлено. Объект TableObject предоставляет свойства и методы, позволяющие управлять объектами таблицы. TableObject – это объект, построенный на основе данных, полученных из модели Power Pivot. Он был введен в Excel 2013.

Свойство XmlMap возвращает объект XmlMap Таблицы, который предоставляет карту XML Таблицы. Свойство имеет тип объекта XmlMap. Объект XmlMap предоставляет свойства и методы, позволяющие управлять XML-картой. Свойство не может быть установлено.

Другие свойства Таблиц

Свойство ListColumn – это элемент в свойстве или коллекции ListColumns. ListColumn – это объект с рядом полезных свойств, включая следующие:

  • Range – ссылки на ячейки в столбце, включая заголовок и итоговые строки, если они включены.
  • DataBodyRange – тип объекта Range, который ссылается на столбец, исключая строки заголовка и итогов. Это пересечение диапазонов, представленных свойством Range объекта ListObject и диапазоном DataBodyRange объекта ListObject.
  • Index – относительный номер индекса столбца, представленного объектом ListColumn.
  • Parent – объект ListObject, которому принадлежит столбец.

ListColumn также включает метод Delete – удаляет столбец из Таблицы.

Каждый объект ListRow в коллекции строк имеет три часто используемых свойства: Range, которое ссылается на ячейки в этой строке; Index, которое является относительным номером индекса этой строки, и Parent, которое ссылается на объект ListObject, содержащий строку. Объект ListRow также имеет один метод Delete, который удаляет строку из таблицы.

Методы объекта Таблицы

Метод Delete удаляет Таблицу, включая все ее значения, формулы и форматирование. Не путайте этот метод с методом Unlist, который преобразует таблицу в обычный диапазон ячеек.

Метод ExportToVisio экспортирует и открывает в Visio динамическую сводную диаграмму в новом документе. Этот метод был добавлен в Excel 2007. Ошибка возникает, если Visio не установлен у вас на ПК (см. также Глава 3. Работа с таблицами Excel).

Метод Publish публикует таблицу в службе SharePoint. Он возвращает URL-адрес опубликованного списка в SharePoint в виде строки:

expression.Publish(Target, LinkSource)

где: expression – переменная, представляющая объект ListObject; Target – одномерный массив типа Variant, содержащий два или три элемента: URL-адрес SharePoint server, отображаемое имя списка и, при необходимости, описание списка; LinkSource – логическое значение. Если оно равно True, создает новую ссылку на новый список SharePoint. Если False, хранит ссылку на текущий список SharePoint и заменяет этот список, или, если нет никакого текущего списка, создает новый список на SharePoint без ссылок на него.

Метод Refresh обновляет таблицу из внешнего источника, если Таблица имеет такую связь. Если Таблица не связана с внешним источником данных, возвращает ошибку. Все изменения, внесенные в таблицу после последнего обновления, будут потеряны.

Метод Resize изменяет диапазон Таблицы на указанный диапазон. Метод принимает один параметр Range, который определяет новый диапазон Таблицы. Если строка заголовка включена, новый диапазон должен включать по крайней мере одну ячейку строки заголовка. Если строка заголовка отключена, новый диапазон должен содержать по крайней мере одну ячейку в первой строке диапазона тела данных. Столбцы можно добавлять и удалять с обоих концов, а строки можно добавлять и удалять только снизу. При удалении строк и столбцов все существующие данные в удаленных строках и столбцах остаются, но теперь находятся вне Таблицы. При добавлении строк и столбцов в Таблицу добавляются любые данные из дополнительных ячеек. После изменения размера структурированные ссылки в формулах в ячейках, отсутствующих в Таблице, преобразуются в абсолютные стандартные ссылки на ячейки. Если Таблица связана со списком SharePoint, можно добавлять и удалять только строки. Попытка добавить или удалить столбцы в связанной таблице приводит к ошибке.

Метод Unlink удаляет любую внешнюю ссылку на данные, если она существует.

Метод Unlist преобразует Таблицу в обычный диапазон ячеек. В интерфейсе Excel это эквивалентно команде Работа с таблицами –> Конструктор –> Параметры стилей таблицы –> Инструменты –> Преобразовать в диапазон.

Другие методы

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

expression.Add(SourceType, Source, LinkSource, _

   XlListObjectHasHeaders, Destination, TableStyleName)

где:

  • expression – переменная, представляющая объект ListObjects,
  • SourceType – передает константу XlListObjectSourceType, которая определяет тип источника, используемого для создания Таблицы. Необязательный параметр. Если опущен, предполагается xlSrcRange.
  • Source – если SourceType = xlSrcRange, то передайте объект Range, представляющий диапазон значений данных для преобразования в Таблицу. Необязательный параметр. Если опущен, используется текущий выбор. Если SourceType = xlSrcExternal, передайте массив строковых значений, указывающих соединение с источником, где элементы массива: 0 – URL-адрес сайта SharePoint, 1 – имя списка SharePoint, 2 – код представления GUID (уникальный шестнадцатеричный идентификатор представления),
  • LinkSource – логическое значение, указывающее, должен ли внешний источник данных быть связан с объектом ListObject. Если SourceType имеет значение xlSrcExternal, то значение по умолчанию равно True, и этот параметр не требуется передавать. Если значение передается и SourceType является xlSrcRange, генерируется ошибка.
  • XlListObjectHasHeaders – передает тип константы xlYesNoGuess, которая может принимать три значения: xlYes, xlNo или xlGuess. Константа указывает, имеют ли импортируемые данные метки столбцов. Если источник не содержит заголовков, Excel автоматически создает заголовки. Необязательный параметр. Если опущено, значение по умолчанию = xlGuess. Имя этого параметра должно было быть HasHeaders, но, когда метод был реализован, разработчики ошибочно использовали XlListObjectHasHeaders.
  • Destination – передает объект Range, который указывает ссылку на одну ячейку в качестве назначения для верхнего левого угла Таблицы. Ошибка генерируется, если диапазон относится к нескольким ячейкам. Этот параметр должен быть указан, если SourceType = xlSrcExternal. Он игнорируется, если SourceType имеет значение xlSrcRange. Диапазон назначения должен находиться на листе, содержащем коллекцию ListObjects, указанную в expression. Столбцы вставляются перед целевым диапазоном, чтобы соответствовать новому списку, предотвращая перезапись существующих данных. Необязательный параметр.
  • TableStyleName – передает имя стиля, который будет применен к Таблице. Необязательный параметр. Если опущен, применяется стиль по умолчанию.

Метод Add объекта ListRows вставляет одну новую строку в таблицу в указанной позиции. Вот синтаксис этого метода:

expression.Add(Position, AlwaysInsert)

где:

  • expression – переменная, представляющая объект ListRows.
  • Position – целое число, определяющее относительное положение новой строки. Новая строка вставляется над текущей строкой в этой позиции. Необязательный параметр. Если опущен, новая строка добавляется в нижнюю часть Таблицы.
  • AlwaysInsert – логическое значение, указывающее, следует ли всегда сдвигать данные в ячейках под последней строкой таблицы при вставке новой строки, независимо от того, является ли строка под таблицей пустой. При значении True ячейки под таблицей сдвигаются на одну строку вниз. При значении False, если строка под Таблицей пуста, Таблица расширяется, чтобы занять (добавить) эту строку без сдвига ячеек под ней; если строка под Таблицей содержит данные, эти ячейки сдвигаются вниз при вставке новой строки.

Метод Add возвращает объект ListRow, представляющий новую строку.

Метод Delete объекта ListRow удаляет строку Таблицы, представленную объектом ListRow.

Метод Add объекта ListColumns вставляет один новый столбец в Таблицу в указанной позиции:

  • expression – переменная, представляющая объект ListColumns.
  • Position – целое число, определяющее относительное положение нового столбца. Новый столбец вставляется перед текущим столбцом в этой позиции. Необязательный параметр. Если этот параметр опущен, новый столбец добавляется в правую часть Таблицы.

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

Метод Delete объекта ListColumn удаляет столбец Таблицы, представленный объектом ListColumn.

Метод Автофильтр объекта Range

Метод позволяет создать критерии Автофильтра для столбца, очистить критерии Автофильтра или переключить статус Автофильтра:

expression.AutoFilter(Field, Criteria1, Operator, _

   Criteria2, VisibleDropDown)

где:

  • expression – выражение, возвращающее объект Range.
  • Field – целочисленное смещение поля, на котором будет основан фильтр, где крайнее левое поле = 1. Необязательный параметр. Если опущен, то состояние Автофильтра (включено/выключено) переключается для всего диапазона. Отключение Автофильтра удаляет раскрывающиеся элементы управления Автофильтра.
  • Criteria1 – критерий в виде числа, строки или массива, например, 20 или "Расход". Можно использовать знаки равенства = и неравенства <>. Чтобы найти несколько строк, используйте функцию Array со значением оператора xlFilterValues, например, Array("Значение 1", "Значение 2"). Подстановочные знаки * (один или несколько символов) и ? (можно использовать любой отдельный символ). Если оператор xlTop10Items, то Criteria1 задает число элементов, например 10. Когда оператор xlFilterDynamic, Criteria1 – это константа xlDynamicFilterCriteria (описана ниже). Необязательный параметр. Если опущен, критерии для столбца очищаются.
  • Operator – передает константу XlAutoFilterOperator, определяющую тип фильтра. Необязательный параметр. Если опущен, то принимается равным 0, и Crtiteria1 рассматривается как простое значение для поиска; в этом случае, если в Crtiteria1 передается массив значений, то используется только последнее значение. Если этот параметр опущен, а Crtiteria1 не указан, то Автофильтр для указанного столбца будет очищен.
  • Criteria2 – второй критерий в виде числа, строки или массива. Он используется с Crtiteria1 и Operator для построения составных критериев или когда Operator = xlFilterValues, а фильтруются дата и время (описано ниже). Необязательный параметр.
  • VisibleDropDown – передает True, чтобы отобразить стрелку раскрывающегося списка Автофильтра для отфильтрованного поля, и False, чтобы скрыть раскрывающийся список Автофильтра для отфильтрованного поля. Необязательный параметр. Если опущен, принимает значение True.

Если заданы критерии фильтрации, то возвращаемое значение является значением Field. При переключении статуса Автофильтра возвращается значение True.

Значения констант оператора XlAutoFilterOperator:

  • xIAnd или 1 – фильтры с логическим И для Criteria1 and Criteria Оба критерия являются строками, задающими условия, например, ">0" и "<100".
  • xlBottom10Items или 4 – находит отображаемые элементы с наименьшим значением, где число элементов задается как число или строка в Criteria1, например, 5 или "5", то есть пять наименьших элементов. Столбец, указанный в параметре Field, должен содержать хотя бы одно число, иначе произойдет ошибка.
  • xlBottom10Percent или 6 – найти отображаемые элементы с наименьшим значением, где процент указан как число или строка в Criteria1, например, 20 или "20" для элементов в нижних 20%. Столбец, указанный в параметре Field, должен содержать хотя бы одно число, иначе произойдет ошибка.
  • xlFilterCellColor или 8 – находит цвет ячейки, где цвет указан как значение RGB в Criteria
  • xlFilterDynamic или 11 – динамический фильтр, где критерий фильтра задается как значение XlDynamicFilterCriteria в Criteria Динамический фильтр – это фильтр, изменяющийся в зависимости от какого-либо другого значения, например сегодняшней даты или среднего значения в столбце.
  • xlFilterFontColor или 9 – находит цвет шрифта, где цвет указан как значение RGB в Criteria
  • xlFilterIcon или 10 – находит значок, указанный в Criteria Значки извлекаются из свойства ActiveWorkbookIconSets. Свойство IconSets представляет собой набор объектов IconSets, в котором каждый набор иконок представляет собой набор из ряда иконок, таких как набор "3 стрелки (цветные)" или "3 Arrows (Colored)". В приведенном ниже примере извлекается первый значок в наборе "3 стрелки (цветные)":

ActiveWorkbook.IconSets(xlIconSet.xl3Arrows).Item(1)

Обратите внимание, что при вводе в редакторе VBA "xlIconSet." (включая точку) появится всплывающий список IntelliSense со всеми доступными ссылками на набор значков.

  • xlFilterValues или 7 – находит несколько значений, заданных в виде массива в Criteria1 или Criteria Значения в массиве должны быть строковыми и точно соответствовать отображаемому значению, если оно числовое; например, если соответствующие значения отображаются как "$25.00", передаваемое значение должно быть"$25.00". Criteria2 используется при поиске дат и времени. При поиске дат и времен массив передается как массив пар значений, где первое значение каждой пары является типом поиска, а второе –датой. Типы поиска: 0 – находит элементы в том же году, что и следующее значение даты / времени; 1 – находит элементы в том же месяце, что и следующее значение даты / времени; 2 – находит элементы на ту же дату, что и следующее значение даты / времени; 3 – находит элементы в тот же час, что и следующее значение даты / времени; 4 – находит элементы в ту же минуту, что и следующее значение даты / времени; 5 – находит элементы в ту же секунду, что и следующее значение даты / времени.

Может быть передано любое количество пар типа поиска и значения даты / времени. Все значения типа поиска должны находиться в нечетных позициях в массиве (1, 3, 5 и т.д.), а все значения даты/времени должны быть в четных позициях (2, 4, 6 и т.д.). Любое значение, переданное для типа поиска, которого нет в приведенном выше списке, создает ошибку. Любое значение, переданное для значения даты/времени, которое не является значением даты/времени, создает ошибку. Допустимо любое значение даты/времени, которое может быть введено в ячейку и распознано как дата. Некоторые примеры значений Criteria2:

Показать все элементы в 2014 году: Array(0, "1/1/2014")

Показать все элементы в 2014 году, когда текущий год 2014: Array(0, "1/1")

Показать все элементы в январе 2014 года: Array(1, "1/1/2014")

Показать все элементы 15 января 2014 года: Array(2, "15/1/2014")

Показывать все элементы 15, 20 и 25 января 2014 года: Array(2, "15/1/2014", 2, "20/1/2014", 2, "25/1/2014")

Показать все элементы в 2013 году и в январе 2014 года: Array(0, "1/1/2013", 1, "1/1/2014")

Показать все элементы в в 3 часа дня 15 января 2014 года: Array(3, "15/1/2014 15:00") или Array(3, "15/1/2014 3 PM")

Показать все элементы в 15:01 15 января 2014 года: Array (3, "15/1/2014 15:01") или Array(3, "15/1/2014 3:01 PM")

  • xlOr или 2 – логическим ИЛИ для Criteria1 and Criteria Оба критерия – это строки, задающие условие, например "<0" и ">100" для значений меньше нуля или больше 100.
  • xlTop10Items или 3 – находит отображаемые элементы с наибольшим значением, где число элементов задается как число или строка в Criteria1, например 5 или "5", то есть пять самых больших элементов. Столбец, указанный в параметре Field, должен содержать хотя бы одно число, иначе произойдет ошибка.
  • xlTop10Percent или 5 – находит отображаемые элементы с наибольшим значением, где процент указан как число или строка в Criteria1, например 20 или "20" для элементов в верхних 20%. Столбец, указанный в параметре Field, должен содержать хотя бы одно число, иначе произойдет ошибка.

Значения констант оператора XlDynamicFilterCriteria:

  • xlFilterToday – фильтрует все значения дат, равные сегодняшнему дню.
  • xlFilterYesterday – фильтрует все значения дат, равные вчерашнему дню.
  • xlFilterTomorrow – фильтрует все значения дат, равные завтрашнему дню.
  • xlFilterThisWeek – фильтрует все значения дат на текущей неделе.
  • xlFilterLastWeek – фильтрует все значения дат за предыдущую неделю.
  • xlFilterNextWeek – фильтрует все значения дат на следующей неделе.
  • xlFilterThisMonth – фильтрует все значения дат в текущем месяце.
  • xlFilterLastMonth – фильтрует все значения дат за предыдущий месяц.
  • xlFilterNextMonth – фильтрует все значения дат в следующем месяце.
  • xlFilterThisQuarter – фильтрует все значения дат в текущем квартале.
  • xlFilterLastQuarter – фильтрует все значения дат в предыдущем квартале.
  • xlFilterNextQuarter – фильтрует все значения дат в следующем квартале.
  • xlFilterThisYear – фильтрует все значения дат в текущем году.
  • xlFilterLastYear – фильтрует все значения дат за предыдущий год.
  • xlFilterNextYear – фильтрует все значения, относящиеся к следующему году.
  • xlFilterYearToDate – фильтрует все значения дат с начала года по сегодня.
  • xlFMterAMDatesInPeriodQuarterl – фильтрует все значения дат в квартале
  • xlFMterAMDatesInPeriodQuarter2 – фильтрует все значения дат в квартале 2.
  • xlFMterAMDatesInPeriodQuarter3 – фильтрует все значения дат в квартале 3.
  • xlFilterAllDatesInPeriodQuarter4 – фильтрует все значения дат в квартале 4.
  • xlFilterAllDatesInPeriodJanuary – фильтрует все значения дат в январе.
  • xlFilterANDatesInPeriodFebruary – фильтрует все значения дат в феврале.
  • xlFilterAllDatesInPeriodMarch – фильтрует все значения дат в марте.
  • xlFilterAllDatesInPeriodApril – фильтрует все значения дат в апреле.
  • xlFilterAllDatesInPeriodMay – фильтрует все значения дат в мае.
  • xlFilterAllDatesInPeriodJune – фильтрует все значения дат в июне.
  • xlFilterAllDatesInPeriodJuly – фильтрует все значения дат в июле.
  • xlFilterAllDatesInPeriodAugust – фильтрует все значения дат в августе.
  • xlFilterAllDatesInPeriodSeptember – фильтрует все значения дат в сентябре.
  • xlFilterAllDatesInPeriodOctober – фильтрует все значения дат в октябре.
  • xlFilterAllDatesInPeriodNovember – фильтрует все значения дат в ноябре.
  • xlFilterAllDatesInPeriodDecember – фильтрует все значения дат в декабре.
  • xlFilterAboveAverage – фильтрует все значения выше среднего.
  • xlFilterBelowAverage – фильтрует все значения ниже среднего.

Доступ к элементам Таблицы

Хотя свойства ListObject, ListColumns, ListRows предоставляют доступ к основным частям таблицы, существуют и другие способы доступа к элементам таблицы с использованием синтаксиса структурированных ссылок, описанного в главе 4. Эти способы могут быть более удобными, в зависимости от стиля программирования и предпочтений. В приведенных ниже примерах предполагается, что есть Таблица с именем "tblRegister" на листе с именем "Register" с заголовками столбцов "Date", "Description", "Category" и "Amount":

Ris. 9.5. Tablitsa

Чтобы использовать структурированную ссылку, используйте объект Range для извлечения диапазона, описанного ссылкой. Объект Range является дочерним объектом многих объектов Excel, включая объекты Application и Worksheet. При использовании объекта Range с объектом Application ссылка должна иметь глобальную область действия. При использовании Range с Worksheet (или Sheet) ссылка может иметь глобальную или локальную (Worksheet) область.

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

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

ThisWorkbook.Worksheets(«Register»).Range(«tblRegister[Date]»)

Application.Range(«tblRegister[Date]»)

Range(«tblRegister[Date]»)

[tblRegister[Date]]

Чтобы соответствовать этому правилу, Excel требует, чтобы каждая Таблица в книге имела уникальное имя. Это правило управляет всеми глобальными именами, а не только именами Таблиц.

Чтобы уменьшить вероятность коллизии имен, можно предварить все имена таблиц общим префиксом, часто называемым «венгерской нотацией», описанной в главе 2, например, "tbl".

Excel 2003 не поддерживает структурированные ссылки. Существуют также некоторые различия между Excel 2007, 2010 и 2013 с точки зрения поддержки структурированных ссылок.

Создание и присвоение имени Таблице

Таблицы создаются с помощью метода Add объекта ListObjects. После создания новой Таблицы свойству DisplayName объекта ListObject присваивается имя новой Таблицы. Имя Таблицы, присваиваемое по умолчанию, зависит от источника Таблицы: xlSrcRange (диапазон данных на листе), xlSrcExternal (внешний источник данных), xlSrcModel (модель данных Power Pivot) и xlSrcQuery (запрос). Тип источника xlSrcXml (источник XML) не рассматривается, но показаны обходные пути.

Использование диапазона данных

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

Dim TableRange As Range

Dim Table As ListObject

Set TableRange = ThisWorkbook.Worksheets(«Register»). _

   Range(«A1»).CurrentRegion

Set Table = ThisWorkbook.Worksheets(«Register»). _

   ListObjects.Add(xlSrcRange, TableRange, ,xlYes)

Table.DisplayName = «tblRegister»

Обратите внимание, что четвертый параметр, xlYes, сообщает Excel, что список данных уже содержит заголовки. В этом примере Таблица будет названа сразу же после ее создания; это поможет вам найти объект ListObject позже.

Использование модели данных Power Pivot

В этом примере для создания соединения с базой данных SQL Server используется объект TableObject. Таблица SQL "Product" добавляется в модель данных Power Pivot. Таблица помещается на рабочий лист "Sheet1" в ячейку A1. Поскольку взаимодействие происходит с моделью данных, то вместо объекта ListObject с xlSrcModel, переданного для SourceType, должен использоваться объект TableObject. Измените текст "YourServerName" на имя нужного SQL-сервера. Используется база данных AdventureWorks2012:

Dim SQLConnection As WorkbookConnection

Dim TargetWorksheet As Worksheet

Dim Table As TableObject

Dim ConnectionString As String

Set TargetWorksheet = ThisWorkbook.Worksheets(«Sheet1»)

ConnectionString = «OLEDB;Provider=SQLOLEDB.1; _

   Integrated Security=SSPI;» & «Initial Catalog _

   =AdventureWorks2012;Data Source=YourServerName»

Set SQLConnection = ActiveWorkbook.Connections.Add2(«FriendlyName», _

   «Description», ConnectionString, «Product», 3, True)

With TargetWorksheet

   Set Table = .ListObjects.Add(SourceType:=xlSrcModel, _

   Source:=SQLConnection, Destination:=.Range(«A1»)).NewTable

End With

Table.ListObject.DisplayName = «tblNewTable»

Константа xlSrcModel была добавлена в Excel 2013.

В следующем примере предполагается, что книга уже имеет соединение SQL Server с Таблицей в модели данных Power Pivot, и задача состоит в том, чтобы извлечь данные из таблицы модели данных в новую Таблицу Excel. Тип источника – xlSrcModel, и предполагается, что имя Таблицы модели данных – "Product". Этот пример работает только в Excel 2013:

Dim ModelSource As Model

Dim SourceTable As ModelTable

Dim TargetWorksheet As Worksheet

Dim Table As TableObject

Set TargetWorksheet = ThisWorkbook.Worksheets(«Sheet1»)

Set ModelSource = ThisWorkbook.Model

Set SourceTable = ModelSource.ModelTables(«Product»)

Set Table = TargetWorksheet.ListObjects.Add(SourceType:=xlSrcModel, _

   Source:=SourceTable.SourceWorkbookConnection, _

   LinkSource:=True, Destination:=DestinationSheet.Range(«A1»)).TableObject

Table.Refresh

Использование запроса Power Query

В этом примере объект QueryTable используется для создания соединения с базой данных SQL Server. Таблица "Product" добавляется на лист "Sheet1" в ячейку А1. Измените текст "YourServerName" на имя нужного SQL-сервера. Используется база данных AdventureWorks2012:

Dim TargetWorksheet As Worksheet

Dim Table As QueryTable

Dim ConnectionString As String

Set TargetWorksheet = ThisWorkbook.Worksheets(«Sheet1»)

ConnectionString = «OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;» _

   & «Initial Catalog=AdventureWorks2012;Data Source=YourServerName»

Set Table = TargetWorksheet.ListObjects.Add(SourceType:=xlSrcExternal, _

   Source:=ConnectionString, LinkSource:=True, _

   Destination:=DestinationSheet.Range(«A1»)).QueryTable

Table.CommandText = Array(«»«AdventureWorks2012»«.»«Production»«.»«Product»«»)

Table.CommandType = xlCmdTable

Table.Refresh BackgroundQuery:=False

Table.ListObject.DisplayName = «tblNewTable»

Константа xlSrcQuery была добавлена в Excel 2007.

При использовании xlSrcExternal необходимо указать параметр назначения. При использовании объекта QueryTable необходимо задать свойства CommandText и CommandType перед обновлением соединения.

В этом примере используется тип источника xlSrcExternal, который используется для любого внешнего подключения к данным. Передача xlSrcQuery для параметра SourceType приводит к тому же результату. Как правило, xlSrcQuery используется для подключения к базе данных, а xlSrcExternal используется для подключения к SharePoint.

Использование источника XML

По замыслу, метод Add объекта ListObjects с типом источника xlSrcXml должен создать объект ListObject, используя в качестве источника XML-файл. Однако этот метод ненадежен, и нет известных рабочих примеров его использования. Для импорта исходного файла XML в Таблицу рекомендуется использовать два метода. Во-первых, необходимо импортировать XML-файл в новую пустую книгу:

Workbooks.OpenXML Filename:=«C:XML File Name.xml», _

   LoadOption:=xlXmlLoadImportToList

Во-вторых, необходимо импортировать XML-файл в существующий лист в указанном диапазоне.:

ActiveWorkbook.XmlImport URL:=«C:XML File Name.xml», _

   ImportMap:=Nothing, Overwrite:=True, _

   Destination:=Range(«A1»)

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

Информация о Таблице

В следующих примерах предполагается, что DataBodyRange является допустимым объектом диапазона. Если в Таблице нет существующих строк (то есть если ListRows.Count равно 0), любая ссылка на DataBodyRange вернет ошибку.

Определение того, существует ли таблица

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

Dim Table As ListObject

Set Table = Nothing

On Error Resume Next

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

On Error GoTo 0

If Table Is Nothing Then

   Debug.Print «Table does not exist»

Else

   Debug.Print «Table exists»

End If

Зачем устанавливать объектную переменную равную Nothing, прежде чем пытаться присвоить ей значение? В приведенном выше случае это не обязательно, поскольку VBA инициализирует каждую переменную, когда она определена с помощью оператора Dim. Но он включен выше в качестве примера написания надежного кода, потому что, если возникает ошибка, переменная не трогается и, если она уже содержит ссылку на другой объект, следующий тест не даст желаемого результата.

Определение адреса таблицы

В следующем примере выводится адрес Таблицы и адрес DataBodyRange Таблицы:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Debug.Print «Table’s address: « & Table.Range.Address

Debug.Print «Table’s data body range address: « _

   & Table.DataBodyRange.Address

Определение количества строк

Количество строк в таблице определяется с помощью свойства Count объекта ListRows:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Debug.Print «Number of rows: « & Table.ListRows.Count

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

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

Количество столбцов в таблице определяется с помощью свойства Count объекта ListColumns:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Debug.Print «Number of columns: « & Table.ListColumns.Count

Определение того, существует ли столбец

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

Dim Table As ListObject

Dim ListColumn As ListColumn

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set ListColumn = Nothing

On Error Resume Next

Set ListColumn = Table.ListColumns(«Description»)

On Error GoTo 0

If ListColumn Is Nothing Then

   Debug.Print «Column does not exist»

Else

   Debug.Print «Column exists»

End If

Добавление строк

Существует несколько способов добавления новых строк в Таблицу. Если вы добавляете одну строку, используйте метод Add объекта ListRows. Он возвращает объект ListRow, который затем можно использовать для добавления значений в эту новую строку:

Dim Table As ListObject

Dim NewRow As ListRow

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set NewRow = Table.ListRows.Add

With NewRow.Range

   .Columns(1).Value = #1/1/2015#

   .Columns(2).Value = «Transaction 20»

   .Columns(3).Value = «Expense»

   .Columns(4).Value = 75

End With

Обратите внимание, что в этом примере параметр Position не был передан методу Add, что привело к добавлению новой строки в конец таблицы. Чтобы вставить новую строку в определенную позицию таблицы, используйте параметр Position.

Чтобы добавить более одной строки в нижнюю часть таблицы, удобнее добавлять строки за один шаг, чем вызывать метод Add объекта ListRows несколько раз. В следующем примере строка итогов отключена, новые данные копируются в пустые ячейки непосредственно под Таблицей, после чего строка итогов включается. (Если функция TotalRow не отключена, Таблица не распознает новые строки и поэтому не расширяется для их включения.) Новые данные копируются из диапазона A2:D11 на листе Data:

Dim Table As ListObject

Dim NewValues As Variant

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

NewValues = ThisWorkbook.Worksheets(«Data»).Range(«A2:D11»).Value

Table.ShowTotals = False

With Table.DataBodyRange

   .Resize(10).Offset(.Rows.Count).Value = NewValues

End With

Table.ShowTotals = True

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

Dim Table As ListObject

Dim NewValues As Variant

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

NewValues = ThisWorkbook.Worksheets(«Data»).Range(«A2:D11»).Value

With Table.DataBodyRange

   .Resize(10).Offset(2).Insert Shift:=xlShiftDown

   .Resize(10).Offset(2).Value = NewValues

End With

Удаление строк

Метод, который вы используете, зависит от того, сколько строк вы хотите удалить.

Удаление одной строки

Для удаления одной строки используется метод Delete объекта ListRow:

Dim Table As ListObject

Dim ListRow as ListRow

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Set ListRow = Table.ListRows(3)

ListRow.Delete

Переменной ListRow присваивается третий объект ListRow в коллекции ListRows, а затем вызывается метод Delete объекта ListRow. Вот альтернативная, более короткая версия примера, которая не требует переменной ListRow:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Table.ListRows(3).Delete

Удаление нескольких строк

Удаление нескольких строк одновременно требует использования метода Delete объекта Range. В следующем примере удаляются 10 строк, начиная со строки 3:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Table.DataBodyRange.Resize(10).Offset(2).Delete

Удаление всех строк

В следующем примере удаляются все строки таблицы:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Table.DataBodyRange.Delete

В этом примере объекту DataBodyRange после завершения кода присваивается значение Nothing. Любые последующие ссылки на этот объект возвращают ошибку, если в Таблицу не добавлена хотя бы одна строка.

Циклы

В первом примере выполняется цикл по всем строкам Таблицы, добавляя в переменную TotalExpenses значения всех строк в столбце Expense (расходы) и выводя результат в окно Immediate:

Dim Table As ListObject

Dim ListRow As ListRow

Dim TotalExpenses As Double

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

For Each ListRow In Table.ListRows

   If ListRow.Range.Columns(3).Value = «Expense» Then

      TotalExpenses = TotalExpenses + ListRow.Range.Columns(4).Value

   End If

Next ListRow

Debug.Print «Total expenses: « & TotalExpenses

Ниже приведен альтернативный метод, использующий имена столбцов:

Dim Table As ListObject

Dim ListRow As ListRow

Dim TotalExpenses As Double

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

For Each ListRow In Table.ListRows

   If Intersect(ListRow.Range, Table.ListColumns(«Category»).Range) _

         .Value = «Expense» Then

      TotalExpenses = TotalExpenses + Intersect(ListRow.Range, Table.

      ListColumns(«Amount»).Range).Value

   End If

Next ListRow

Debug.Print «Total expenses: « & TotalExpenses

Во втором примере выполняется цикл по столбцам Таблицы, выводя имя каждого столбца на экран с помощью коллекции ListColumns и оператора For / Each:

Dim Table As ListObject

Dim ListColumn As ListColumn

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

For Each ListColumn In Table.ListColumns

   Debug.Print ListColumn.Name

Next ListColumn

Фильтрация

Одной из самых мощных особенностей Таблиц является их способность фильтровать строки. Объектная модель Excel предоставляет объект AutoFilter (дочерний элемент объекта ListObject) и метод AutoFilter (дочерний элемент объекта Range), что позволяет полностью контролировать процесс фильтрации в VBA. Используйте объект ListObject.AutoFilter для проверки текущих настроек Автофильтра, обновления Автофильтра и очистки Автофильтра. Используйте метод Range.AutoFilter для задания критериев Автофильтра.

Включение и выключение Автофильтра

Вы включаете и выключаете Автофильтр, задавая свойству ShowAutoFilter значения True (вкл.) и False (выкл.). В следующем примере показано, как включить Автофильтр:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Table.ShowAutoFilter = True

Поскольку Автофильтр – это объект, который не имеет значения при отключенном Автофильтре, любой код, ссылающийся на какие-либо свойства и методы объекта Автофильтра, будет генерировать ошибку, если Автофильтр отключен. Чтобы избежать ошибок, убедитесь, что Автофильтр включен, и получите доступ к свойствам и методам объекта Автофильтра только в этом случае. Примеры ниже показывают, как осуществить эту проверку.

Вы также можете включать и отключать Автофильтр, повторно вызывая метод Range.AutoFilter без каких-либо параметров. Использование этого метода просто переключает состояние Автофильтра.

Определение состояния фильтрации

Объект Автофильтр используется для определения того, включен ли Автофильтр:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

If Table.ShowAutoFilter Then

   Debug.Print «AutoFilter is on»

Else

   Debug.Print «AutoFilter is off»

End If

Если Автофильтр включен, вы используете свойство FilterMode объекта Автофильтра, чтобы определить, установлены ли критерии фильтрации:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

If Table.ShowAutoFilter Then

   If Table.AutoFilter.FilterMode Then

      Debug.Print «Filtering is active»

   Else

      Debug.Print «Filtering is inactive»

   End If

Else

   Debug.Print «AutoFilter is off»

End If

Определение того, фильтруется ли столбец

Если Автофильтр включен, можно использовать свойство On объекта Filter, чтобы определить, имеет ли столбец активный критерий фильтра:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

If Table.ShowAutoFilter Then

   If Table.AutoFilter.Filters(3).On Then

      Debug.Print «Column 3 is being filtered»

   End If

Else

   Debug.Print «AutoFilter is off»

End If

Создание фильтров

Вы создаете (применяете) фильтры по одному столбцу за раз. Для добавления и удаления критериев фильтрации используется метод AutoFilter объекта Range. При применении критерия Автофильтра строка заголовка включается автоматически. В примерах ниже предполагается, что Таблица не имеет активных критериев фильтрации: Ниже приведены примеры, каждый из которых начинается с этих двух строк кода. Предполагается, что Таблица не имеет активных критериев фильтрации:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

В следующем примере фильтруются строки со значением Expense в третьем столбце.:

Table.Range.AutoFilter Field:=3, Criteria1:=«Expense»

А здесь фильтруются строки с Expense или Income в третьем столбце.:

Table.Range.AutoFilter Field:=3, _

   Criteria1:=Array(«Expense», «Income»), Operator:=xlFilterValues

Ниже показаны только строки со значениями во втором столбце, которые начинаются с Transaction:

Table.Range.AutoFilter Field:=2, Criteria1:=«Transaction*»

Строки в четвертом столбце со значениями больше нуля:

Table.Range.AutoFilter Field:=4, Criteria1:=«>0»

Строки с Income в третьем столбце и значениями более 100 – в четвертом:

Table.Range.AutoFilter Field:=3, Criteria1:=«Income»

Table.Range.AutoFilter Field:=4, Criteria1:=«>100»

Повторное применение критериев активного фильтра

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

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

If Table.ShowAutoFilter Then

   Table.AutoFilter.ApplyFilter

End If

Очистка фильтра одного столбца

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

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

Table.Range.AutoFilter Field:=3

Очистка всех фильтров

Вы можете очистить критерии фильтрации для всех столбцов за один шаг, не отключая Автофильтр, вызвав метод ShowAllData:

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

If Table.ShowAutoFilter Then

   Table.AutoFilter.ShowAllData

End If

Скрытие раскрывающихся элементов управления по столбцам

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

Dim Table As ListObject

Set Table = ThisWorkbook.Worksheets(«Register»).ListObjects(«tblRegister»)

If Table.ShowAutoFilter Then

   Table.Range.AutoFilter Field:=2, VisibleDropDown:=False

End If

Пользовательские процедуры

В следующих разделах приведены некоторые пользовательские процедуры. Более надежные версии этих программ и ряд других программ, а также полезные утилиты и библиотеки доступны по адресу http://exceltables.com/.

Делаем объемную вставку

Следующая функция вставляет массив значений в Таблицу и возвращает новые строки в виде диапазона. Если задана строка, то значения вставляются выше этой строки; в противном случае значения добавляются в нижнюю часть Таблицы. Функция также сопоставляет столбцы значений со столбцами Таблицы с помощью параметра ColumnAssignmentS. Дополнительные сведения о параметрах см. в комментариях к процедуре.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

Public Function BulkInsertIntoTable( _

      ByVal Table As ListObject, _

      ByVal Values As Variant, _

      Optional ByVal Position As Long = 1, _

      Optional ByVal ColumnAssignments As Variant _

   ) As Range

‘ Insert an array of values into a Table. Optionally specify the row before

which the new rows are inserted. Optionally specify how the columns are

‘ assigned. The new rows in the Table are returned as a Range.

Syntax

‘ BulkInsertIntoTable(Table, Values, Position, ColumnAssignments)

Table A Table object.

‘ Values — A single value, a single dimension array of values, or a two

dimension array of values.

‘ Position — The row number before which the new rows are inserted. Optional.

If omitted then the new rows are appended to the end of the Table.

‘ ColumnAssignments — A single dimension array of integer values specifying

which Table column receives what column of values in the Values parameter.

‘ Each element in the array is a column number in the Table. The position of

the element in the array corresponds to the column in the Values array.

‘ Optional. If omitted then the values are placed in column order starting in

the first Table column. For example, passing Array(2,3,1) results in this

‘ column mapping:

Values column 1 is placed in Table column 2.

‘ Values column 2 is placed in Table column 3.

Values column 3 is placed in Table column 1.

Dim Calculation As XlCalculation

Dim ScreenUpdating As Boolean

Dim Result As Long

Dim TwoDimensionArray As Boolean

Dim WorkArray As Variant

Dim Column As Long

Dim SourceColumn As Long

Dim TargetColumn As Long

Dim ShowTotals As Boolean

Dim InsertRange As Range

‘ Exit if no values to insert

If IsEmpty(Values) Then Exit Function

Calculation = Application.Calculation

Application.Calculation = xlCalculationManual

ScreenUpdating = Application.ScreenUpdating

Application.ScreenUpdating = False

Normalize Values parameter must be a twodimension array

On Error Resume Next

Result = LBound(Values, 2)

TwoDimensionArray = Err.Number = 0

On Error GoTo 0

If Not TwoDimensionArray Then

   If Not IsArray(Values) Then

      Values = Array(Values)

   End If

   ReDim WorkArray(1 To 1, 1 To UBound(Values) LBound(Values) + 1)

   For Column = 1 To UBound(WorkArray, 2)

      WorkArray(1, Column) = Values(Column 1 + LBound(Values))

   Next Column

   Values = WorkArray

End If

‘ Normalize Position parameter

If Position < 0 Then

   Position = Table.ListRows.Count

End If

Position = Application.Max(1, Application.Min(Position, _

   Table.ListRows.Count+ 1))

Save total row setting and disable total

ShowTotals = Table.ShowTotals

Table.ShowTotals = False

‘ Insert the new rows

If Table.ListRows.Count > 0 And Position <= Table.ListRows.Count Then

Table.DataBodyRange.Resize(UBound(Values)). _

Offset(Position — 1).InsertShift:=xlShiftDown

End If

If Table.ListRows.Count > 0 Then

Set InsertRange = Table.DataBodyRange.Resize _

(UBound(Values)).Offset(Position — 1)

Else

Set InsertRange = Table.InsertRowRange.Resize(UBound(Values))

End If

If IsEmpty(ColumnAssignments) Or IsMissing(ColumnAssignments) Then

   InsertRange.Value = Values

Else

   For TargetColumn = LBound(ColumnAssignments) To _

      UBound(ColumnAssignments)

      SourceColumn = TargetColumn — LBound(ColumnAssignments) + 1

      If ColumnAssignments(TargetColumn) >= 1 And _

         ColumnAssignments(TargetColumn) <= _

            Table.ListColumns.Count Then

         InsertRange.Columns(ColumnAssignments(TargetColumn)) _

            .Value = Application.Index(Values, , SourceColumn)

      End If

   Next TargetColumn

End If

Set BulkInsertIntoTable = InsertRange

Restore the total row setting

Table.ShowTotals = ShowTotals

Application.Calculation = Calculation

Application.ScreenUpdating = ScreenUpdating

End Function

Восстановление форматирования и формул

Обычно Таблица поддерживает одинаковое форматирование и формулы во всех строках, исключая строки заголовка и итоговые строки. При изменении форматирования или формулы в ячейке столбца Таблицы Excel применяет это новое форматирование или формулу ко всему столбцу. Форматирование и формулы автоматически применяются к новым строкам по мере их добавления.

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

Процедура ниже выполняет это с помощью метода изменения размера Таблицы. Сначала Таблица изменяется, чтобы быть только одной строкой. Затем форматирование и формулы удаляются из всех строк таблицы от строки 2 до последней строки плюс одна строка. Наконец, диапазон Таблицы возвращается к тому, что было. На этом заключительном этапе Excel должен применить форматирование и формулы в первой строке ко всем строкам ниже первой строки. В результате получается последовательно отформатированная таблица, использующая первую строку данных в качестве шаблона для всех остальных строк. Код предполагает, что в Таблице есть по крайней мере одна строка данных:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

Public Sub RepairTable( _

      ByVal Table As ListObject _

   )

‘ Repair the Table’s formatting and formulas by making them consistent down the

‘ entire length of each column.

‘ Syntax

‘ RepairTable(Table)

Table A Table object (ListObject object).

Dim RowCount As Long

Dim ListColumn As ListColumn

Dim ShowTotals As Boolean

RowCount = Table.ListRows.Count

If RowCount < 2 Then Exit Sub

With Table

   ShowTotals = .ShowTotals

   .ShowTotals = False

   .Resize .HeaderRowRange.Resize(2)

   For Each ListColumn In .ListColumns

      With ListColumn.DataBodyRange.Resize( _

         Application.Max(RowCount, 1)).Offset(1)

         If Left(.Rows(1).Formula, 1) = «=» Then

            .Cells.Clear

         Else

            .Cells.ClearFormats

         End If

     End With

   Next ListColumn

   .Resize .HeaderRowRange.Resize(1 + RowCount)

   .ShowTotals = ShowTotals

End With

End Sub

Копирование стиля Таблицы в новую книгу

Нет простого способа скопировать стиль Таблицы из одной книги в другую. Следующий пример кода копирует стиль, присвоенный Таблице с именем "tblRegister", в книгу "Destination Workbook. xlsx":

Sub ExportTableStyle()

   Dim Source As Workbook

   Dim Target As Workbook

   Dim Table As ListObject

   Set Source = ThisWorkbook

   Set Target = Workbooks(«Destination Workbook.xlsx»)

   Set Table = Source.Worksheets(«Register»).ListObjects(«tblRegister»)

   Target.Worksheets.Add Before:=Target.Worksheets(1)

   Table.Range.Copy Target.Worksheets(1).Range(«A1»)

   Target.Worksheets(1).Delete

End Sub

[1] Различают три основных разновидности массивов: с отсчетом от нуля (zero-based), с отсчетом от единицы (one-based) и с отсчетом от специфического значения заданного программистом (n-based).

 

zenija2007

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

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

я нашел только Range(«Таблица1»).Rows, а дальше возможно есть команда для добавления новой строки в конце? Думал Range(«Таблица1»).Rows.Insert, но на непустой таблице он срабатывает странных образом — может добавить 2 пустых строки перед первой записью, или полностью деформировать таблицу.

Изменено: zenija200708.12.2016 06:03:54

 

SAS888

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

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

#2

08.12.2016 06:24:27

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

Код
Union(Range("Таблица1"), Range("Таблица1").Offset(1)).Name = "Таблица1"

Если же требуется не просто изменить размер именованного диапазона, а именно ВСТАВИТЬ строку (ячейки ниже таблицы) и переопределить этот именованный диапазон, то можно сделать так:

Код
Sub qq()
    With Range("Таблица1")
        Intersect(Rows(.Row + .Rows.Count), .EntireColumn).Insert xlDown
        Union(Range("Таблица1"), .Offset(1)).Name = "Таблица1"
    End With
End Sub

Изменено: SAS88808.12.2016 08:00:08

Чем шире угол зрения, тем он тупее.

 

zenija2007

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

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

ругается, что такое имя уже существует. вы не расширяете, а пытаетесь пересоздать.

 

JayBhagavan

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

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

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

#4

08.12.2016 11:39:03

Код
    ActiveSheet.ListObjects("Данные").ListRows.Add AlwaysInsert:=False

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

zenija2007

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

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

JayBhagavan, а можно как-то избавиться от ActiveSheet, чтобы скрипт работал из любого листа? Я и стал использовать имена таблиц и диапазонов, чтобы убрать привязку к листам.

 

JayBhagavan

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

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

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

#6

09.12.2016 07:06:32

читаем справку по ListObjects

Ответ был дан согласно составленной Вами темы:

Цитата
VBA добавление строки в таблицу с именем

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

zenija2007

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

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

#7

09.12.2016 07:21:02

Цитата
JayBhagavan написал:
Ответ был дан согласно составленной Вами темы:

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

Код
Range("Черно").EntireRow.End(xlDown).Offset(1).Value = 5
Range("Черно").EntireRow.End(xlDown).Clear
 

RAN

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

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

#8

09.12.2016 09:34:48

Код
Sub мяу()
    Const RangeName$ = "Данные"
    With Range(shName).Parent.ListObjects(RangeName)
        .ListRows.Add AlwaysInsert:=False
    End With
End Sub

Примечание
Работает только в стандартном модуле

Изменено: RAN09.12.2016 09:36:00

 

Андрей VG

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

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

Excel 2016, 365

#9

09.12.2016 10:32:16

Доброе время суток
Андрей (RAN), а Parent то зачем?

Код
    If Not Range("Данные").ListObject Is Nothing Then
        Range("Данные").ListObject.ListRows.Add AlwaysInsert:=False
    End If
 

JayBhagavan

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

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

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

Андрей VG, спасибо за Ваш подход. Взял на заметку. :)

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

RAN

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

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

#11

09.12.2016 11:00:42

Андрей, хитро. Так не пробовал. Все больше «в лоб».  :)

Содержание

  1. Метод ListRows.Add (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Замечания
  6. Пример
  7. Поддержка и обратная связь
  8. Excel VBA Insert Row: Step-by-Step Guide and 9 Code Examples to Insert Rows with Macros
  9. Insert Rows in Excel
  10. Excel VBA Constructs to Insert Rows
  11. Insert Rows with the Range.Insert Method
  12. Purpose of Range.Insert
  13. Syntax of Range.Insert
  14. Parameters of Range.Insert
  15. How to Use Range.Insert to Insert Rows
  16. Specify Rows with the Worksheet.Rows Property
  17. Purpose of Worksheet.Rows
  18. Syntax of Worksheet.Rows
  19. How to Use Worksheet.Rows to Insert Rows
  20. Specify the Active Cell with the Application.ActiveCell Property
  21. Purpose of Application.ActiveCell
  22. Syntax of Application.ActiveCell
  23. How to Use Application.ActiveCell To Insert Rows
  24. Specify a Cell Range with the Worksheet.Range Property
  25. Purpose of Worksheet.Range
  26. Syntax of Worksheet.Range
  27. Parameters of Worksheet.Range
  28. How to Use Worksheet.Range to Insert Rows
  29. Specify a Cell with the Worksheet.Cells and Range.Item Properties
  30. Purpose of Worksheet.Cells and Range.Item
  31. Syntax of Worksheet.Cells and Range.Item
  32. Parameters of Worksheet.Cells and Range.Item
  33. How to use Worksheet.Cells and Range.Item to Insert Rows
  34. Specify a Cell Range a Specific Number of Rows Below or Above a Cell or Cell Range with the Range.Offset Property
  35. Purpose of Range.Offset
  36. Syntax of Range.Offset
  37. Parameters of Range.Offset
  38. How to Use Range.Offset to Insert Rows
  39. Specify Entire Row with the Range.EntireRow Property
  40. Purpose of Range.EntireRow
  41. Syntax of Range.EntireRow
  42. How to Use Range.EntireRow to Insert Rows
  43. Clear Row Formatting with the Range.ClearFormats Method
  44. Purpose of Range.ClearFormats
  45. Syntax of Range.ClearFormats
  46. How to Use Range.ClearFormats to Insert Rows
  47. Copy Rows with the Range.Copy Method
  48. Purpose of Range.Copy
  49. Syntax of Range.Copy
  50. Parameters of Range.Copy
  51. How to Use Range.Copy to Insert Rows
  52. Related VBA and Macro Tutorials
  53. Excel VBA Code Examples to Insert Rows
  54. Example Workbooks
  55. Example #1: Excel VBA Insert Row
  56. VBA Code to Insert Row
  57. Process Followed by Macro
  58. VBA Statement Explanation
  59. Effects of Executing the Macro
  60. Example #2: Excel VBA Insert Multiple Rows
  61. VBA Code to Insert Multiple Rows
  62. Process Followed by Macro
  63. VBA Statement Explanation
  64. Effects of Executing the Macro
  65. Example #3: Excel VBA Insert Row with Same Format as Row Above
  66. VBA Code to Insert Row with Same Format as Row Above
  67. Process Followed by Macro
  68. VBA Statement Explanation
  69. Effects of Executing the Macro
  70. Example #4: Excel VBA Insert Row with Same Format as Row Below
  71. VBA Code to Insert Row with Same Format as Row Below
  72. Process Followed by Macro
  73. VBA Statement Explanation
  74. Effects of Executing the Macro
  75. Example #5: Excel VBA Insert Row without Formatting
  76. VBA Code to Insert Row without Formatting
  77. Process Followed by Macro
  78. VBA Statement Explanation
  79. Effects of Executing the Macro
  80. Example #6: Excel VBA Insert Row Below Active Cell
  81. VBA Code to Insert Row Below Active Cell
  82. Process Followed by Macro
  83. VBA Statement Explanation
  84. Effects of Executing the Macro
  85. Example #7: Excel VBA Insert Copied Row
  86. VBA Code to Insert Copied Row
  87. Process Followed by Macro
  88. VBA Statement Explanation
  89. Effects of Executing the Macro
  90. Example #8: Excel VBA Insert Blank Rows Between Rows in a Data Range
  91. VBA Code to Insert Blank Rows Between Rows in a Data Range
  92. Process Followed by Macro
  93. VBA Statement Explanation
  94. Effects of Executing the Macro
  95. Example #9: Excel VBA Insert a Number of Rows Every Number of Rows in a Data Range
  96. VBA Code to Insert a Number of Rows Every Number of Rows in a Data Range
  97. Process Followed by Macro
  98. VBA Statement Explanation
  99. Effects of Executing the Macro

Метод ListRows.Add (Excel)

Добавляет новую строку в таблицу, представленную указанным ListObject.

Синтаксис

expression. Add (Position, AlwaysInsert)

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

Параметры

Имя Обязательный или необязательный Тип данных Описание
Position Необязательный Variant Целое число. Определяет относительную позицию новой строки.
AlwaysInsert Необязательный Variant Логическое значение. Указывает, следует ли всегда перемещать данные в ячейках под последней строкой таблицы при вставке новой строки независимо от того, пуста ли строка под таблицей. Если значение true, ячейки под таблицей будут смещены вниз на одну строку.

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

Возвращаемое значение

Объект ListRow , представляющий новую строку.

Замечания

Если позиция не указана, добавляется новая нижняя строка. Если параметр AlwaysInsert не указан, ячейки под таблицей будут смещены вниз на одну строку (аналогично указанию True).

Пример

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

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

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

Источник

Excel VBA Insert Row: Step-by-Step Guide and 9 Code Examples to Insert Rows with Macros

In certain cases, you may need to automate the process of inserting a row (or several rows) in a worksheet. This is useful, for example, when you’re (i) manipulating or adding data entries, or (ii) formatting a worksheet that uses blank rows for organization purposes.

The information and examples in this VBA Tutorial should allow you to insert rows in a variety of circumstances.

This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by clicking the button below.

Use the following Table of Contents to navigate to the section you’re interested in.

Table of Contents

Insert Rows in Excel

When working manually with Excel, you can insert rows in the following 2 steps:

  1. Select the row or rows above which to insert the row or rows.
  2. Do one of the following:
    1. Right-click and select Insert.
    2. Go to Home > Insert > Insert Sheet Rows.
    3. Use the “Ctrl + Shift + +” keyboard shortcut.

You can use the VBA constructs and structures I describe below to automate this process to achieve a variety of results.

Excel VBA Constructs to Insert Rows

Insert Rows with the Range.Insert Method

Purpose of Range.Insert

Use the Range.Insert method to insert a cell range into a worksheet. The 2 main characteristics of the Range.Insert method are the following:

  1. Range.Insert can insert a single cell or a cell range. For purposes of this VBA Tutorial, you’re interested in inserting entire rows.
  2. To make space for the newly-inserted cells, Range.Insert shifts other cells away.

Syntax of Range.Insert

“expression” is a Range object. Therefore, I simplify as follows:

Parameters of Range.Insert

  1. Parameter: Shift.
    • Description: Specifies the direction in which cells are shifted away to make space for the newly-inserted row.
    • Optional/Required: Optional.
    • Data type: Variant.
    • Values: Use a constant from the xlInsertShiftDirection Enumeration:
      • xlShiftDown or -4121: Shifts cells down.
      • xlShiftToRight or -4161: Shifts cells to the right.
    • Default: Excel decides based on the range’s shape.
    • Usage notes: When you insert a row: (i) use xlShiftDown or -4121, or (ii) omit parameter and rely on the default behavior.
  2. Parameter: CopyOrigin.
    • Description: Specifies from where (the origin) is the format for the cells in the newly inserted row copied.
    • Optional/Required: Optional.
    • Data type: Variant.
    • Values: A constant from the xlInsertFormatOrigin Enumeration:
      • xlFormatFromLeftOrAbove or 0: Newly-inserted cells take formatting from cells above or to the left.
      • xlFormatFromRightOrBelow or 1: Newly-inserted cells take formatting from cells below or to the right.
    • Default: xlFormatFromLeftOrAbove or 0. Newly-inserted cells take the formatting from cells above or to the left.

How to Use Range.Insert to Insert Rows

Use the Range.Insert method to insert a row into a worksheet. Use a statement with the following structure:

For these purposes:

  • Range: Range object representing an entire row. Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents the entire row. Please refer to the sections about the Rows and EntireRow properties below.
  • xlInsertFormatOriginConstant: xlFormatFromLeftOrAbove or xlFormatFromRightOrBelow. xlFormatFromLeftOrAbove is the default value. Therefore, when inserting rows with formatting from row above, you can usually omit the CopyOrigin parameter.

You can usually omit the Shift parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Specify Rows with the Worksheet.Rows Property

Purpose of Worksheet.Rows

Use the Worksheet.Rows property to return a Range object representing all the rows within the worksheet the property works with.

Worksheet.Rows is read-only.

Syntax of Worksheet.Rows

“expression” is a Worksheet object. Therefore, I simplify as follows:

How to Use Worksheet.Rows to Insert Rows

Use the Worksheet.Rows property to specify the row or rows above which new rows are inserted.

To insert a row, use a statement with the following structure:

“row#” is the number of the row above which the row is inserted.

To insert multiple rows, use a statement with the following structure:

“firstRow#” is the row above which the rows are inserted. The number of rows VBA inserts is calculated as follows:

Specify the Active Cell with the Application.ActiveCell Property

Purpose of Application.ActiveCell

Use the Application.ActiveCell property to return a Range object representing the active cell.

Application.ActiveCell is read-only.

Syntax of Application.ActiveCell

“expression” is the Application object. Therefore, I simplify as follows:

How to Use Application.ActiveCell To Insert Rows

When you insert a row, use the Application.ActiveCell property to return the active cell. This allows you to use the active cell as reference for the row insertion operation.

Use the Range.Offset property to return a Range object a specific number of rows above or below the active cell. Use the Range.EntireRow property to return a Range object representing the entire row or rows above which to insert the new row. Please refer to the sections about the Offset and EntireRow properties below.

To insert a row above the active cell, use the following statement:

To insert a row a specific number of rows above or below the active cell, use a statement with the following structure:

Specify a Cell Range with the Worksheet.Range Property

Purpose of Worksheet.Range

Use the Worksheet.Range property to return a Range object representing a single cell or a cell range.

Syntax of Worksheet.Range

“expression” is a Worksheet object. Therefore, I simplify as follows:

Parameters of Worksheet.Range

  1. Parameter: Cell1.
    • Description:
      • If you use Cell1 alone (omit Cell2), Cell1 specifies the cell range.
      • If you use Cell1 and Cell2, Cell1 specifies the cell in the upper-left corner of the cell range.
    • Required/Optional: Required.
    • Data type: Variant.
    • Values:
      • If you use Cell1 alone (omit Cell2): (i) range address as an A1-style reference in language of macro, or (ii) range name.
      • If you use Cell1 and Cell2: (i) Range object, (ii) range address, or (iii) range name.
  2. Parameter: Cell2.
    • Description: Cell in the lower-right corner of the cell range.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values: (i) Range object, (ii) range address, or (iii) range name.

How to Use Worksheet.Range to Insert Rows

When you insert a row, use the Worksheet.Range property to return a cell or cell range. This allows you to use a specific cell or cell range as reference for the row insertion operation.

Use the Range.Offset property to return a Range object a specific number of rows above or below the cell or cell range. Use the Range.EntireRow property to return a Range object representing the entire row or rows above which to insert the new row or rows. Please refer to the sections about the Offset and EntireRow properties below.

To insert rows above the cell range specified by Worksheet.Range, use a statement with the following structure:

To insert rows a specific number of rows above or below the cell range specified by Worksheet.Range use a statement with the following structure:

If the cell range represented by the Worksheet.Range property spans more than 1 row, the Insert method inserts several rows. The number of rows inserted is calculated as follows:

Please refer to the section about the Worksheet.Rows property above for further information about this calculation.

Specify a Cell with the Worksheet.Cells and Range.Item Properties

Purpose of Worksheet.Cells and Range.Item

Use the Worksheet.Cells property to return a Range object representing all the cells within a worksheet.

Once your macro has all the cells within the worksheet, use the Range.Item property to return a Range object representing one of those cells.

Syntax of Worksheet.Cells and Range.Item

Worksheet.Cells

“expression” is a Worksheet object. Therefore, I simplify as follows:

Range.Item

“expression” is a Range object. Therefore, I simplify as follows:

Worksheet.Cells and Range.Item Together

Considering the above:

However, Item is the default property of the Range object. Therefore, you can generally omit the Item keyword before specifying the RowIndex and ColumnIndex arguments. I simplify as follows:

Parameters of Worksheet.Cells and Range.Item

  1. Parameter: RowIndex.
    • Description:
      • If you use RowIndex alone (omit ColumnIndex), RowIndex specifies the index of the cell you work with. Cells are numbered from left-to-right and top-to-bottom.
      • If you use RowIndex and ColumnIndex, RowIndex specifies the row number of the cell you work with.
    • Required/Optional: Required.
    • Data type: Variant.
    • Values: You usually specify RowIndex as a value.
  2. Parameter: ColumnIndex.
    • Description: Column number or letter of the cell you work with.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values: You usually specify ColumnIndex as a value (column number) or letter within quotations (“”).

How to use Worksheet.Cells and Range.Item to Insert Rows

When you insert a row, use the Worksheet.Cells and Range.Item properties to return a cell. This allows you to use a specific cell as reference for the row insertion operation.

Use the Range.Offset property to return a Range object a specific number of rows above or below the cell. Use the Range.EntireRow property to return a Range object representing the entire row above which to insert the row. Please refer to the sections about the Offset and EntireRow properties below.

To insert a row above the cell specified by Worksheet.Cells, use a statement with the following structure:

To insert a row a specific number of rows above or below the cell specified by Worksheet.Cells, use a statement with the following structure:

Specify a Cell Range a Specific Number of Rows Below or Above a Cell or Cell Range with the Range.Offset Property

Purpose of Range.Offset

Use the Range.Offset property to return a Range object representing a cell range located a number of rows or columns away from the range the property works with.

Syntax of Range.Offset

“expression” is a Range object. Therefore, I simplify as follows:

Parameters of Range.Offset

  1. Parameter: RowOffset.
    • Description: Number of rows by which cell or cell range is offset.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values:
      • Positive number: Moves down the worksheet.
      • Negative number: Moves up the worksheet.
      • 0: Stays on the same row.
    • Default: 0. Stays on the same row.
  2. Parameter: ColumnOffset.
    • Description: Number of columns by which cell or cell range is offset.
    • Required/Optional: Optional.
    • Data type: Variant.
    • Values:
      • Positive number: Moves towards the right of the worksheet.
      • Negative number: Moves towards the left of the worksheet.
      • 0: Stays on the same column.
    • Default: 0. Stays on the same column.
    • Usage notes: When you insert a row, you can usually omit the ColumnOffset parameter. You’re generally interested in moving a number of rows (not columns) above or below.

How to Use Range.Offset to Insert Rows

When you insert a row, use the Range.Offset property to specify a cell or cell range located a specific number of rows below above another cell or cell range. This allows you to use this new cell or cell range as reference for the row insertion operation.

Use properties such as Application.ActiveCell, Worksheet.Range and Worksheet.Cells to specify the base range the Offset property works with. Please refer to the sections about the ActiveCell, Range and Cells properties above.

Specify Entire Row with the Range.EntireRow Property

Purpose of Range.EntireRow

Use the Range.EntireRow property to return a Range object representing the entire row or rows containing the cell range the property works with.

Range.EntireRow is read-only.

Syntax of Range.EntireRow

“expression” is a Range object. Therefore, I simplify as follows:

How to Use Range.EntireRow to Insert Rows

When you insert a row, use the Range.EntireRow property to return the entire row or rows above which the new row or rows are inserted.

Use properties such as Application.ActiveCell, Worksheet.Range and Worksheet.Cells to specify the range the EntireRow property works with. Please refer to the sections about the ActiveCell, Range and Cells properties above.

Clear Row Formatting with the Range.ClearFormats Method

Purpose of Range.ClearFormats

Use the Range.ClearFormats method to clear the formatting of a cell range.

Syntax of Range.ClearFormats

“expression” is a Range object. Therefore, I simplify as follows:

How to Use Range.ClearFormats to Insert Rows

The format of the newly-inserted row is specified by the CopyOrigin parameter of the Range.Insert method. Please refer to the description of Range.Insert and CopyOrigin above.

When you insert a row, use the Range.ClearFormats method to clear the formatting of the newly-inserted rows. Use a statement with the following structure after the statement that inserts the new row (whose formatting you want to clear):

“Range” is a Range object representing the newly-inserted row.

Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents the newly-inserted row. Please refer to the sections about the Rows and EntireRow properties above.

Copy Rows with the Range.Copy Method

Purpose of Range.Copy

Use the Range.Copy method to copy a cell range to another cell range or the Clipboard.

Syntax of Range.Copy

“expression” is a Range object. Therefore, I simplify as follows:

Parameters of Range.Copy

  1. Parameter: Destination.
    • Description: Specifies the destination cell range to which the copied cell range is copied.
    • Required/Optional: Optional parameter.
    • Data type: Variant.
    • Values: You usually specify Destination as a Range object.
    • Default: Cell range is copied to the Clipboard.
    • Usage notes: When you insert a copied row, omit the Destination parameter to copy the row to the Clipboard.

How to Use Range.Copy to Insert Rows

Use the Range.Copy method to copy a row which you later insert.

Use a statement with the following structure before the statement that inserts the row:

“Range” is a Range object representing an entire row.

Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents a row. Please refer to the sections about the Rows and EntireRow properties above.

  • General VBA constructs and structures:
    • Introduction to Excel VBA constructs and structures.
    • The Excel VBA Object Model.
    • How to declare variables in Excel VBA.
    • Excel VBA data types.
  • Practical VBA applications and macro examples:
    • How to copy and paste with Excel VBA.

You can find additional VBA and Macro Tutorials in the Archives.

Excel VBA Code Examples to Insert Rows

Example Workbooks

This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I explain below. If you want to follow and practice, you can get immediate free access to these example workbooks by clicking the button below.

Each worksheet within the workbook contains a single data range. Most of the entries simply state “Data”.

Example #1: Excel VBA Insert Row

VBA Code to Insert Row

The following macro inserts a row below row 5 of the worksheet named “Insert row”.

Process Followed by Macro

VBA Statement Explanation

Worksheets(“Insert row”).Rows(6).Insert Shift:=xlShiftDown
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(6).
    • VBA construct: Worksheets.Rows property.
    • Description: Returns a Range object representing row 6 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #2 above.
  4. Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

Effects of Executing the Macro

The following GIF illustrates the results of executing this macro. As expected, VBA inserts a row below row 5 of the worksheet.

Example #2: Excel VBA Insert Multiple Rows

VBA Code to Insert Multiple Rows

The following macro inserts 5 rows below row 10 of the worksheet named “Insert row”.

Process Followed by Macro

VBA Statement Explanation

Worksheets(“Insert row”).Rows(“11:15”).Insert Shift:=xlShiftDown
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(“11:15”).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing rows 11 to 15 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description:
      • Inserts new rows above the rows returned by item #2 above.
      • The number of inserted rows is equal to the number of rows returned by item #2 above. This is calculated as follows:

In this example:

  • Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the rows inserted by item #3 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
  • Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. As expected, VBA inserts 5 rows below row 10 of the worksheet.

    Example #3: Excel VBA Insert Row with Same Format as Row Above

    VBA Code to Insert Row with Same Format as Row Above

    The following macro (i) inserts a row below row 20, and (ii) applies the formatting of row 20 to the newly-inserted row.

    Process Followed by Macro

    VBA Statement Explanation

    Worksheets(“Insert row”).Rows(21).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
    1. Item: Worksheets(“Insert row”).
      • VBA construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the “Insert row” worksheet.
    2. Item: Rows(21).
      • VBA construct: Worksheet.Rows property.
      • Description: Returns a Range object representing row 21 of the worksheet returned by item #1 above.
    3. Item: Insert.
      • VBA construct: Range.Insert method.
      • Description: Inserts a new row above the row returned by item #2 above.
    4. Item: Shift:=xlShiftDown.
      • VBA construct: Shift parameter of Range.Insert method.
      • Description:
        • Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
        • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
    5. Item: CopyOrigin:=xlFormatFromLeftOrAbove.
      • VBA construct: CopyOrigin parameter of Range.Insert method.
      • Description:
        • Sets formatting of row inserted by item #3 above to be equal to that of row above (xlFormatFromLeftOrAbove).
        • You can usually omit this parameter. xlFormatFromLeftOrAbove (or 0) is the default value of CopyOrigin.

    Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. As expected, VBA (i) inserts a row below row 20, and (ii) applies the formatting of row 20 to the newly-inserted row.

    Example #4: Excel VBA Insert Row with Same Format as Row Below

    VBA Code to Insert Row with Same Format as Row Below

    The following macro (i) inserts a row below row 25, and (ii) applies the formatting of the row below to the newly-inserted row.

    Process Followed by Macro

    VBA Statement Explanation

    Worksheets(“Insert row”).Rows(26).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
    1. Item: Worksheets(“Insert row”).
      • VBA construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the “Insert row” worksheet.
    2. Item: Rows(26).
      • VBA construct: Worksheet.Rows property.
      • Description: Returns a Range object representing row 26 of the worksheet returned by item #1 above.
    3. Item: Insert.
      • VBA construct: Range.Insert method.
      • Description: Inserts a new row above the row returned by item #2 above.
    4. Item: Shift:=xlShiftDown.
      • VBA construct: Shift parameter of Range.Insert method.
      • Description:
        • Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
        • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
    5. Item: CopyOrigin:=xlFormatFromRightOrBelow.
      • VBA construct: CopyOrigin parameter of Range.Insert method.
      • Description: Sets formatting of row inserted by item #3 above to be equal to that of row below (xlFormatFromRightOrBelow).

    Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. As expected, VBA (i) inserts a row below row 25, and (ii) applies the formatting of the row below to the newly-inserted row.

    Example #5: Excel VBA Insert Row without Formatting

    VBA Code to Insert Row without Formatting

    The following macro inserts a row below row 30 without applying the formatting from the rows above or below the newly- inserted row.

    Process Followed by Macro

    VBA Statement Explanation

    Lines #4 and #5: Dim myNewRowNumber As Long | myNewRowNumber = 31
    1. Item: Dim myNewRowNumber As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (myNewRowNumber) as of the Long data type.
        • myNewRowNumber represents the number of the newly inserted row.
    2. Item: myNewRowNumber = 31.
      • VBA construct: Assignment statement.
      • Description: Assigns the value 31 to myNewRowNumber
    Lines #6 and #9: With Worksheets(“Insert row”) | End With
    1. Item: With | End With.
      • VBA construct: With… End With statement.
      • Description: Statements within the With… End With statement (lines #7 and #8 below) are executed on the worksheet returned by item #2 below.
    2. Item: Worksheets(“Insert row”).
      • VBA construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the “Insert row” worksheet.
    Line #7: .Rows(myNewRowNumber).Insert Shift:=xlShiftDown
    1. Item: Rows(myNewRowNumber).
      • VBA construct: Worksheet.Rows property.
      • Description:
        • Returns a Range object representing a row (whose number is represented by myNewRowNumber) of the worksheet in the opening statement of the With… End With statement (line #6 above).
        • In this example, myNewRowNumber equals 31. Therefore, Worksheet.Rows returns row 31 prior to the insertion of the new row. This is a different row from that returned by Worksheet.Rows in line #8 below.
        • This line #7 returns a row prior to the row insertion. This line is that above which the new row is inserted.
        • Line #8 below returns a row after the row insertion. This line is the newly-inserted row.
    2. Item: Insert.
      • VBA construct: Range.Insert method.
      • Description: Inserts a new row above the row returned by item #1 above.
    3. Item: Shift:=xlShiftDown.
      • VBA construct: Shift parameter of Range.Insert method.
      • Description:
        • Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
        • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
    Line #8: .Rows(myNewRowNumber).ClearFormats
    1. Item: Rows(myNewRowNumber).
      • VBA construct: Worksheet.Rows property.
      • Description:
        • Returns a Range object representing a row (whose number is represented by myNewRowNumber) of the worksheet in the opening statement of the With… End With statement (line #6 above).
        • In this example, myNewRowNumber equals 31. Therefore, Worksheet.Rows returns row 31 after the insertion of the new row. This is a different row from that returned by Worksheet.Rows in line #7 above.
        • This line #8 returns a row after the row insertion. This line is the newly-inserted row.
        • Line #7 above returns a row prior to the row insertion. This line is that below the newly-inserted row.
    2. Item: ClearFormats.
      • VBA construct: Range.ClearFormats method.
      • Description: Clears the formatting of the row returned by item #1 above.

    Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. As expected, VBA inserts a row below row 30 without applying the formatting from the rows above or below the newly- inserted row.

    Example #6: Excel VBA Insert Row Below Active Cell

    VBA Code to Insert Row Below Active Cell

    The following macro inserts a row below the active cell.

    Process Followed by Macro

    VBA Statement Explanation

    ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown
    1. Item: ActiveCell.
      • VBA construct: Application.ActiveCell property.
      • Description: Returns a Range object representing the active cell.
    2. Item: Offset(1).
      • VBA construct: Range.Offset property.
      • Description:
        • Returns a Range object representing the cell range 1 row below the cell returned by item #1 above.
        • In this example, Range.Offset returns the cell immediately below the active cell.
    3. Item: EntireRow:
      • VBA construct: Range.EntireRow property.
      • Description: Returns a Range object representing the entire row containing the cell range returned by item #2 above.
    4. Item: Insert.
      • VBA construct: Range.Insert method.
      • Description: Inserts a new row above the row returned by item #3 above.
    5. Item: Shift:=xlShiftDown.
      • VBA construct: Shift parameter of Range.Insert method.
      • Description:
        • Shifts rows down (xlShiftDown) to make space for the row inserted by item #4 above.
        • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

    Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. When I execute the macro, the active cell is B35. As expected, inserts a row below the active cell.

    Example #7: Excel VBA Insert Copied Row

    VBA Code to Insert Copied Row

    The following macro (i) copies row 45, and (ii) inserts the copied row below row 40.

    Process Followed by Macro

    VBA Statement Explanation

    Lines #4 and #7: With Worksheets(“Insert row”) | End With
    1. Item: With | End With.
      • VBA construct: With… End With statement.
      • Description: Statements within the With… End With statement (lines #5 and #6 below) are executed on the worksheet returned by item #2 below.
    2. Item: Worksheets(“Insert row”).
      • VBA construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the “Insert row” worksheet.
    Line #5: .Rows(45).Copy
    1. Item: Rows(45).
      • VBA construct: Worksheet.Rows property.
      • Description: Returns a Range object representing row 45 of the worksheet in the opening statement of the With… End With statement (line #4 above).
    2. Item: Copy.
      • VBA construct: Range.Copy method.
      • Description: Copies the row returned by item #1 above to the Clipboard.
    Line #6: .Rows(41).Insert Shift:=xlShiftDown
    1. Item: Rows(41).
      • VBA construct: Worksheet.Rows property.
      • Description: Returns a Range object representing row 41 of the worksheet in the opening statement of the With… End With statement (line #4 above).
    2. Item: Insert.
      • VBA construct: Range.Insert method.
      • Description:
        • Inserts a new row above the row returned by item #1 above.
        • The newly-inserted row isn’t blank. VBA inserts the row copied by line #5 above.
    3. Item: Shift:=xlShiftDown.
      • VBA construct: Shift parameter of Range.Insert method.
      • Description:
        • Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
        • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
    Line #8: Application.CutCopyMode = False
    1. Item: Application.CutCopyMode = False.
      • VBA construct: Application.CutCopyMode property.
      • Description: Cancels (False) the Cut or Copy mode and removes the moving border that accompanies this mode.

    Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. As expected, VBA (i) copies row 45, and (ii) inserts the copied row below row 40.

    Example #8: Excel VBA Insert Blank Rows Between Rows in a Data Range

    VBA Code to Insert Blank Rows Between Rows in a Data Range

    The following macro inserts blank rows within the specified data range. This results in all rows within the data range being separated by a blank row.

    Process Followed by Macro

    VBA Statement Explanation

    Lines #4 through #9: Dim myFirstRow As Long | Dim myLastRow As Long | Dim myWorksheet As Worksheet | Dim iCounter As Long | myFirstRow = 5 | Set myWorksheet = Worksheets(“Insert blank rows”)
    1. Item: Dim myFirstRow As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (myFirstRow) as of the Long data type.
        • myFirstRow represents the number of the first row with data in the data range you work with.
    2. Item: Dim myLastRow As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (myLastRow) as of the Long data type.
        • myLastRow represents the number of the last row with data in the data range you work with.
    3. Item: Dim myWorksheet As Worksheet.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new object variable (myWorksheet) to reference a Worksheet object.
        • myWorksheet represents the worksheet you work with.
    4. Item: Dim iCounter As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (iCounter) as of the Long data type.
        • iCounter represents a loop counter.
    5. Item: myFirstRow = 5.
      • VBA construct: Assignment statement.
      • Description: Assigns the value 5 to myFirstRow.
    6. Item: Set myWorksheet = Worksheets(“Insert blank rows”).
      • VBA constructs:
        • Set statement.
        • Workbooks.Worksheets property.
      • Description: Assigns the Worksheet object representing the “Insert blank rows” worksheet to myWorksheet.
    Lines #10 through #15: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    1. Item: myLastRow =.
      • VBA construct: Assignment statement.
      • Description: Assigns the value returned by items #2 through #9 below to myLastRow.
    2. Item: myWorksheet.Cells.
      • VBA construct: Worksheet.Cells property.
      • Description: Returns a Range object representing all cells on myWorksheet.
    3. Item: Find.
      • VBA construct: Range.Find method.
      • Description:
        • Finds information in the cell range returned by item #2 above and returns a Range object representing the first cell where the information is found.
        • In this example, the Range object Range.Find returns represents the last cell with data in last row with data in myWorksheet.
    4. Item: What:=”*”.
      • VBA construct: What parameter of Range.Find method.
      • Description: Specifies the data Range.Find searches for. The asterisk (*) is a wildcard and, therefore, Range.Find searches for any character sequence.
    5. Item: LookIn:=xlFormulas.
      • VBA construct: LookIn parameter of Range.Find method.
      • Description: Specifies that Range.Find looks in formulas (xlFormulas).
    6. Item: LookAt:=xlPart.
      • VBA construct: LookAt parameter of Range.Find method.
      • Description: Specifies that Range.Find looks at (and matches) a part (xlPart) of the search data.
    7. Item: SearchOrder:=xlByRows.
      • VBA construct: SearchOrder parameter of Range.Find method.
      • Description: Specifies that Range.Find searches by rows (xlByRows).
    8. Item: SearchDirection:=xlPrevious.
      • VBA construct: SearchDirection parameter of Range.Find method.
      • Description: Specifies that Range.Find searches for the previous match (xlPrevious).
    9. Item: Row.
      • VBA construct: Range.Row property.
      • Description:
        • Returns the row number of the Range object returned by item #3 above.
        • In this example, the number returned by Range.Row corresponds to the last row with data in myWorksheet.
    Lines #16 and #18: For iCounter = myLastRow To (myFirstRow + 1) Step -1 | Next iCounter
    1. Item: For | Next iCounter.
      • VBA construct: For… Next statement.
      • Description:
        • Repeats the statement inside the For… Next loop (line #17 below) a specific number of times.
        • In this example:
          • The macro starts on the last row of the data range as specified by item #2 below.
          • Every iteration, the loop counter decreases by 1, as specified by item #4 below. Therefore, the macro moves to the previous row.
          • The macro exits the loop after working with the second row in the data range (myFirstRow + 1), as specified by item #3 below.
    2. Item: iCounter = myLastRow.
      • VBA construct: Counter and Start of For… Next statement.
      • Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
    3. Item: To (myFirstRow + 1).
      • VBA construct: End of For… Next statement.
      • Description: Specifies the value represented by myFirstRow plus 1 (myFirstRow + 1) as the final value of the loop counter.
    4. Item: Step -1.
      • VBA construct: Step of For… Next statement.
      • Description: Specifies that the loop counter (iCounter) decreases by 1 (-1) every loop iteration.
    Line #17: myWorksheet.Rows(iCounter).Insert Shift:=xlShiftDown
    1. Item: myWorksheet.Rows(iCounter).
      • VBA construct: Worksheet.Rows property.
      • Description:
        • Returns a Range object representing the row (whose number is represented by iCounter) of myWorksheet.
        • Worksheet.Rows returns the row through which the macro is currently looping.
    2. Item: Insert.
      • VBA construct: Range.Insert method.
      • Description:
        • Inserts a new row above the row returned by item #1 above.
        • The macro loops through each line in the data range (excluding the first) as specified by lines #16 and #18 above. Therefore, Range.Insert inserts a row between all rows with data.
    3. Item: Shift:=xlShiftDown.
      • VBA construct: Shift parameter of Range.Insert method.
      • Description:
        • Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
        • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.

    Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. As expected, VBA inserts blank rows within the specified data range. This results in all rows within the data range being separated by a blank row.

    Example #9: Excel VBA Insert a Number of Rows Every Number of Rows in a Data Range

    VBA Code to Insert a Number of Rows Every Number of Rows in a Data Range

    The following macro inserts 2 rows every 3 rows within the specified data range.

    Process Followed by Macro

    VBA Statement Explanation

    Lines #4 through 13: Dim myFirstRow As Long | Dim myLastRow As Long | Dim myNRows As Long | Dim myRowsToInsert As Long | Dim myWorksheet As Worksheet | Dim iCounter As Long | myFirstRow = 5 | myNRows = 3 | myRowsToInsert = 2 | Set myWorksheet = Worksheets(“Insert M rows every N rows”)
    1. Item: Dim myFirstRow As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (myFirstRow) as of the Long data type.
        • myFirstRow represents the number of the first row with data in the data range you work with.
    2. Item: Dim myLastRow As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (myLastRow) as of the Long data type.
        • myLastRow represents the number of the last row with data in the data range you work with.
    3. Item: Dim myNRows As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (myNRows) as of the Long data type.
        • myNRows represents the number of rows per block. The macro doesn’t insert rows between these rows.
    4. Item: Dim myRowsToInsert As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (myRowsToInsert) as of the Long data type.
        • myRowsToInsert represents the number of rows to insert.
    5. Item: Dim myWorksheet As Worksheet.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new object variable (myWorksheet) to reference a Worksheet object.
        • myWorksheet represents the worksheet you work with.
    6. Item: Dim iCounter As Long.
      • VBA construct: Dim statement.
      • Description:
        • Declares a new variable (iCounter) as of the Long data type.
        • iCounter represents a loop counter.
    7. Item: myFirstRow = 5.
      • VBA construct: Assignment statement.
      • Description: Assigns the value 5 to myFirstRow.
    8. Item: myNRows = 3.
      • VBA construct: Assignment statement.
      • Description: Assigns the value 3 to myNRows.
    9. Item: myRowsToInsert = 2.
      • VBA construct: Assignment statement.
      • Description: Assigns the value 2 to myRowsToInsert.
    10. Item: Set myWorksheet = Worksheets(“Insert M rows every N rows”).
      • VBA constructs:
        • Set statement.
        • Workbooks.Worksheets property.
      • Description: Assigns the Worksheet object representing the “Insert M rows every N rows” worksheet to myWorksheet.
    Lines #14 through #19: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    1. Item: myLastRow =.
      • VBA construct: Assignment statement.
      • Description: Assigns the value returned by items #2 through #9 below to myLastRow.
    2. Item: myWorksheet.Cells.
      • VBA construct: Worksheet.Cells property.
      • Description: Returns a Range object representing all cells on myWorksheet.
    3. Item: Find.
      • VBA construct: Range.Find method.
      • Description:
        • Finds information in the cell range returned by item #2 above and returns a Range object representing the first cell where the information is found.
        • In this example, the Range object Range.Find returns represents the last cell with data in last row with data in myWorksheet.
    4. Item: What:=”*”.
      • VBA construct: What parameter of Range.Find method.
      • Description: Specifies the data Range.Find searches for. The asterisk (*) is a wildcard and, therefore, Range.Find searches for any character sequence.
    5. Item: LookIn:=xlFormulas.
      • VBA construct: LookIn parameter of Range.Find method.
      • Description: Specifies that Range.Find looks in formulas (xlFormulas).
    6. Item: LookAt:=xlPart.
      • VBA construct: LookAt parameter of Range.Find method.
      • Description: Specifies that Range.Find looks at (and matches) a part (xlPart) of the search data.
    7. Item: SearchOrder:=xlByRows.
      • VBA construct: SearchOrder parameter of Range.Find method.
      • Description: Specifies that Range.Find searches by rows (xlByRows).
    8. Item: SearchDirection:=xlPrevious.
      • VBA construct: SearchDirection parameter of Range.Find method.
      • Description: Specifies that Range.Find searches for the previous match (xlPrevious).
    9. Item: Row.
      • VBA construct: Range.Row property.
      • Description:
        • Returns the row number of the Range object returned by item #3 above.
        • In this example, the number returned by Range.Row corresponds to the last row with data in myWorksheet.
    Lines #20 and #22: For iCounter = myLastRow To (myFirstRow + myNRows) Step -1 | Next iCounter
    1. Item: For | Next iCounter.
      • VBA construct: For… Next statement.
      • Description:
        • Repeats the statement inside the For… Next loop (line #21 below) a specific number of times.
        • In this example:
          • The macro starts on the last row of the data range as specified by item #2 below.
          • Every iteration, the loop counter decreases by 1, as specified by item #4 below. Therefore, the macro moves to the previous row.
          • The macro exits the loop after working with the row below the first block of rows you want to keep, as specified by item #3 below. Each block of rows has a number of rows equal to myNRows.
          • In this example, myNRows equals 3. Therefore, the macro exits the loop after working with the fourth row in the data range.
    2. Item: iCounter = myLastRow.
      • VBA constructs: Counter and Start of For… Next statement.
      • Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
    3. Item: To (myFirstRow + myNRows).
      • VBA construct: End of For… Next statement.
      • Description: Specifies the value represented by myFirstRow plus myNRows (myFirstRow + myNRows) as the final value of the loop counter.
    4. Item: Step -1.
      • VBA construct: Step of For… Next statement.
      • Description: Specifies that the loop counter (iCounter) decreases by 1 (-1) every loop iteration.
    Line #21: If (iCounter – myFirstRow) Mod myNRows = 0 Then myWorksheet.Rows(iCounter & “:” & iCounter + myRowsToInsert – 1).Insert Shift:=xlShiftDown
    1. Item: If | Then.
      • VBA construct: If… Then… Else statement.
      • Description: Conditionally executes the statement specified by items #3 and #4 below, subject to condition specified by item #2 below being met.
    2. Item: (iCounter – myFirstRow) Mod myNRows = 0.
      • VBA constructs:
        • Condition of If… Then… Else statement.
        • Numeric expression with Mod operator.
      • Description:
        • The Mod operator (Mod) (i) divides one number (iCounter – myFirstRow) by a second number (myNRows), and (ii) returns the remainder of the division.
        • The condition ((iCounter – myFirstRow) Mod myNRows = 0) is met (returns True) if the remainder returned by Mod is 0.
        • The condition is met (returns True) every time the macro loops through a row above which blank rows should be added.
          • iCounter represents the number of the row through which the macro is currently looping.
          • (iCounter – myFirstRow) is the number of rows (in the data range) above the row through which the macro is currently looping.
          • ((iCounter – myFirstRow) Mod myNRows) equals 0 when the number of rows returned by (iCounter – myFirstRow) is a multiple of myNRows. This ensures that the number of rows left above the row through which the macro is currently looping can be appropriately separated into blocks of myNRows. In this example, myNRows equals 3. Therefore, the condition is met every 3 rows.
    3. Item: myWorksheet.Rows(iCounter & “:” & iCounter + myRowsToInsert – 1).
      • VBA constructs:
        • Statements executed if the condition specified by item #2 above is met.
        • Worksheet.Rows property.
      • Description:
        • Returns an object representing several rows of myWorksheet. The first row is represented by iCounter. The last row is represented by (iCounter + myRowsToInsert – 1).
        • The number of rows Worksheet.Rows returns equals the number of rows to insert (myRowsToInsert).
          • iCounter represents the number of the row through which the macro is currently looping.
          • (iCounter + myRowsToInsert – 1) returns a row located a number of rows (myRowsToInsert – 1) below the row through which the macro is currently looping. In this example, myRowsToInsert equals 2. Therefore, (iCounter + myRowsToInsert – 1) returns a row located 1 (2 – 1) rows below the row through which the macro is currently looping.
    4. Item: Insert.
      • VBA construct: Range.Insert method.
      • Description:
        • Inserts new rows above the rows returned by item #3 above.
        • The number of inserted rows is equal to the value of myRowsToInsert. This is calculated as follows:

    In this example, if the current value of iCounter is 8:

  • Item: Shift:=xlShiftDown.
    • VBA construct: Shift parameter of Range.Insert method.
    • Description:
      • Shifts rows down (xlShiftDown) to make space for the rows inserted by item #4 above.
      • You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
  • Effects of Executing the Macro

    The following GIF illustrates the results of executing this macro. As expected, VBA inserts 2 rows every 3 rows within the specified data range.

    Источник

    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    1

    Excel

    Добавление строк в таблицу

    20.05.2018, 20:40. Показов 29566. Ответов 52


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

    Ребят, нужно по условию добавлять строки в нужные места. Никак не соображу как. Подскажите пожалуйста. Спасибо



    0



    Programming

    Эксперт

    94731 / 64177 / 26122

    Регистрация: 12.04.2006

    Сообщений: 116,782

    20.05.2018, 20:40

    Ответы с готовыми решениями:

    Добавление в таблицу строк по заданному количеству)
    Ребят, как в моем примере сделать так, чтобы если указал в UserForm 80 месяцев (допустим), то на…

    Из исходной таблицы в n строк и 6 столбцов нужно сделать таблицу-результат из кучи строк и 6 столбцов
    Добрый вечер,

    учусь в универcитете, начал изучать макросы и подвернулась &quot;интересная&quot; задача -…

    Добавление данных в таблицу
    Уважаемые форумчане, помогите, пожалуйста, решить следующую задачу:

    Имеется &quot;Умная таблица&quot;, в…

    Добавление записей в таблицу
    помогите разобраться как как добавлять в ячейки листа значения.
    есть три листбокса, по нажатию на…

    52

    3827 / 2254 / 751

    Регистрация: 02.11.2012

    Сообщений: 5,930

    21.05.2018, 09:04

    2

    файл в студию и описание что да как согласно файла.



    1



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    21.05.2018, 09:39

     [ТС]

    3

    Нужно сделать когда 15 столбец пустой, добавлялась вниз строка.
    Незнаю как



    0



    1813 / 1135 / 346

    Регистрация: 11.07.2014

    Сообщений: 4,002

    21.05.2018, 09:41

    4

    Цитата
    Сообщение от mor_sergey
    Посмотреть сообщение

    Никак не соображу как

    А вам пока можно и не соображать, зксель сам создаст макрос добавления строки.
    Вкладка Разработчик — Запись макроса — Ок Потом встать на нужную строку и нажать правую кнопку мыши, выбрать Добавить строку и потом Остановить запись. Получите макрос для добавления (из него можно взять только две строчки кода. Перед ними ставите ваше условие оператором If ….. End If и всё готово



    1



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    21.05.2018, 09:50

     [ТС]

    5

    Пробывал…Вот:
    Selection.ListObject.ListRows.Add (3)

    И добавляет на строку вверх. Мне нужно insert и вниз. Всю голову сломал



    0



    1813 / 1135 / 346

    Регистрация: 11.07.2014

    Сообщений: 4,002

    21.05.2018, 11:25

    6

    mor_sergey, ну так и вставайте (выделяйте) строку на одну ниже



    1



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    21.05.2018, 11:35

     [ТС]

    7

    я пишу прогу по учету СИЗ. основное и самое сложное казалось бы сделал….а тут такая ерунда и непонимаю.может просто устал.напишите просто код.невыходит ничего.



    0



    shanemac51

    Модератор

    Эксперт MS Access

    11341 / 4660 / 748

    Регистрация: 07.08.2010

    Сообщений: 13,496

    Записей в блоге: 4

    21.05.2018, 11:58

    8

    попробуйте

    Visual Basic
    1
    2
    3
    4
    5
    
    Sub Макрос6()
    '    Range("N6").Select
        Selection.ListObject.ListRows.Add AlwaysInsert:=True
        Range("N7").Select
    End Sub



    2



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    21.05.2018, 12:30

     [ТС]

    9

    только выделяет.вставки строки нет.буду думать дальше. Спасибо



    0



    Burk

    1813 / 1135 / 346

    Регистрация: 11.07.2014

    Сообщений: 4,002

    21.05.2018, 18:46

    10

    mor_sergey, что-то трудно разобрать, что за простушку вы не понимаете, если учитывать, что вы там почти всё сделали. Пусть вам нужно вставить строку после некоторой строки с номером N. Это сделать так

    Visual Basic
    1
    
     Rows(N+1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

    И вставится пустая после строки N. Рекодер так и пишет.



    2



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    21.05.2018, 20:02

     [ТС]

    11

    Ребят, уж простите дебила. Убей непойму как добавить ВНИЗ по условию из моего примера ВЫШЕ строки



    0



    Burk

    1813 / 1135 / 346

    Регистрация: 11.07.2014

    Сообщений: 4,002

    22.05.2018, 04:49

    12

    mor_sergey, ну это, похоже, безнадежно. ВОСПОЛЬЗУЙТЕСЬ ВСТАВКОЙ, КОТОРУЮ Я НАПИСАЛ, ИЛИ ОБЪЯСНИТЕ, ПОЧЕМУ ОНА ВАМ НЕ ПОДХОДИТ!. не пойму пишется раздельно

    Добавлено через 43 минуты
    mor_sergey, N — номер, нужной вам строки

    Visual Basic
    1
    2
    3
    
    If Cells(N, 15) = "" Then 
      Rows(N+1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    End If



    2



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    22.05.2018, 09:25

     [ТС]

    13

    Дружище спасибо огромное. работает.додумываю под свои нужды.пример во вкладке. В 9 столбце между 2 и 3 строчкой вставить значения из 10 столбца под (таблицей).и так с каждой строкой столбца 9) Очень мне помог в любом случае.спасибо



    0



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    22.05.2018, 09:42

     [ТС]

    14

    поправка……В10 столбце умной таблицы между 2 и 3 строчкой вставить значения из 10 столбца (под таблицей).и так с каждой строкой столбца 9)



    0



    1813 / 1135 / 346

    Регистрация: 11.07.2014

    Сообщений: 4,002

    22.05.2018, 11:33

    15

    mor_sergey, мутно написано. Надо добавить в книгу1 ещё одну страницу, на которой нужно изобразить первый лист с вашими вставками, т.е. показать желаемый конечный результат
    А может это промто номер строки по порядку?



    1



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    22.05.2018, 11:51

     [ТС]

    16

    Вот посмотрите.



    0



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    22.05.2018, 11:53

     [ТС]

    17

    Вот, посмотрите



    0



    Burk

    1813 / 1135 / 346

    Регистрация: 11.07.2014

    Сообщений: 4,002

    22.05.2018, 15:57

    18

    mor_sergey, всегда будут добавляться 7 строк?
    А почему вы не решаетесь такую простую добавку сделать самостоятельно или хотя бы попробовать. Ведь всего-то нужно код с добавкой строки (Insert) заключить в цикл

    Visual Basic
    1
    2
    3
    4
    
    For i = 1 to 7
    'сюда строка кода добавки строки c Insert и потом
    Cells(N+1,10)= 8-i
    next



    2



    77 / 11 / 0

    Регистрация: 28.03.2018

    Сообщений: 828

    22.05.2018, 16:24

     [ТС]

    19

    Дружище, спасибо тебе огромное. До цикла я уже додумался. Теперь незнаю как со следующими строками быть. К тем, что ниже, тоже такой цикл применить нужно. Но дело в том, что нумерация строк меняется. А количество не постоянное (не 7). зависит от должности (к каждой привязаны определенные СИЗ)…они на другом листе. я заполняю таблицу целиком через форму (комбобоксы, листбоксы, текстбоксы)……прорабатываю другой вариант заполнения БД. не через форму, а напрямую в экселе……и, заполнив колонки с 1 по 9 остальные отрабатывает макрос.
    Оказалось сложнее, чем код из формы. не учел, что с низу вверх повидимому нужно формировать.тут подумать нужно



    0



    1813 / 1135 / 346

    Регистрация: 11.07.2014

    Сообщений: 4,002

    22.05.2018, 17:00

    20

    mor_sergey, вам надо продумать систему, например, набирать числа 1-7 нет смысла, наверняка нумерация начинается с 1. Поэтому для должностей можно создать информационную таблицу, в которой указывается количество строчек этой должности, например, Токарь — 10 повар — 3 начальник -1
    Вы, видимо, не читали правила, кнопка Спасибо есть на экране справа. ТОлько нажимайте на неё на основных сообщениях для тех, кто вам помогает, для меня не нажимайте на каждое, только на существенное.



    1



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