Excel vba цикл по всем листам

Аннотация

Данная статья содержит Microsoft Visual Basic для приложений макроса (процедура Sub), который в цикле проходит через все листы активной книги. Этот макрос также отображается имя каждого листа.

Дополнительная информация

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

  1. Введите следующий код макроса в лист модуля.

          Sub WorksheetLoop()         Dim WS_Count As Integer         Dim I As Integer         ' Set WS_Count equal to the number of worksheets in the active         ' workbook.         WS_Count = ActiveWorkbook.Worksheets.Count         ' Begin the loop.         For I = 1 To WS_Count            ' Insert your code here.            ' The following line shows how to reference a sheet within            ' the loop by displaying the worksheet name in a dialog box.            MsgBox ActiveWorkbook.Worksheets(I).Name         Next I      End Sub

  2. Чтобы запустить макрос, поместите курсор в строку, которая считывает «Sub WorksheetLoop()» и нажмите клавишу F5.

Макрос будет цикла книги и отображает окно сообщения с именем другого листа при каждом выполнении цикла. Обратите внимание, что этот макрос будет отображать только имена листов; он будет отображаться имена других типов листов в книге. Можно также использовать цикл через все листы в книге с помощью цикла «For Each».

  1. Введите следующий код макроса в лист модуля.

          Sub WorksheetLoop2()         ' Declare Current as a worksheet object variable.         Dim Current As Worksheet         ' Loop through all of the worksheets in the active workbook.         For Each Current In Worksheets            ' Insert your code here.            ' This line displays the worksheet name in a message box.            MsgBox Current.Name         Next      End Sub

  2. Чтобы запустить макрос, поместите курсор в строку, которая считывает «Sub WorksheetLoop2()» и нажмите клавишу F5.

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

Ссылки

Дополнительные сведения о получении справки по Visual Basic для приложений обратитесь к следующей статье Microsoft Knowledge Base:

163435 VBA: программные ресурсы для Visual Basic для приложений

226118 OFF2000: программные ресурсы для Visual Basic для приложений

Нужна дополнительная помощь?

Summary

This article contains a Microsoft Visual Basic for Applications macro (Sub procedure) that loops through all the worksheets in the active workbook. This macro also displays the name of each worksheet.

More Information

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. To try the sample macro, follow these steps:

  1. Type the following macro code into a new module sheet.

          Sub WorksheetLoop()

    Dim WS_Count As Integer
    Dim I As Integer

    ' Set WS_Count equal to the number of worksheets in the active
    ' workbook.
    WS_Count = ActiveWorkbook.Worksheets.Count

    ' Begin the loop.
    For I = 1 To WS_Count

    ' Insert your code here.
    ' The following line shows how to reference a sheet within
    ' the loop by displaying the worksheet name in a dialog box.
    MsgBox ActiveWorkbook.Worksheets(I).Name

    Next I

    End Sub

  2. To run the macro, position the insertion point in the line that reads «Sub WorksheetLoop(),» and press F5.

The macro will loop through the workbook and display a message box with a different worksheet name each time it runs through the loop. Note that this macro will only display worksheet names; it will not display the names of other types of sheets in the workbook.

You can also loop through all of the worksheets in the workbook by using a ‘For Each’ loop.

  1. Enter the following macro code into a new module sheet.

          Sub WorksheetLoop2()

    ' Declare Current as a worksheet object variable.
    Dim Current As Worksheet

    ' Loop through all of the worksheets in the active workbook.
    For Each Current In Worksheets

    ' Insert your code here.
    ' This line displays the worksheet name in a message box.
    MsgBox Current.Name
    Next

    End Sub

  2. To run the macro, position the insertion point in the line that reads «Sub WorksheetLoop2(),» and press F5.

This macro works identically to the WorksheetLoop macro, except that it uses a different type of loop to process all of the worksheets in the active workbook.

References

For additional information about getting help with Visual Basic for Applications, please see the following article in the Microsoft Knowledge Base:

163435 VBA: Programming Resources for Visual Basic for Applications

226118 OFF2000: Programming Resources for Visual Basic for Applications

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Перебор листов в книге Excel циклом For Each… Next с копированием данных из этих листов и вставкой в новый лист той же книги с помощью кода VBA.

Условие задачи по перебору листов

Есть книга Excel с неизвестным количеством рабочих листов с данными. Необходимо выполнить следующие действия:

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

Для открытия книги (получения полного имени) будем использовать диалоговое окно выбора файлов GetOpenFilename, а для перебора листов — цикл For Each… Next.

Пример кода для перебора листов в книге Excel циклом For Each… Next с частичным копированием данных на отдельный лист:

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

Sub CopyDataFromAllSheets()

Dim wb As Workbook, newws As Worksheet, ws As Worksheet, n As Long

n = 1

‘Выбираем, открываем нужную книгу и присваиваем ссылку на нее переменной wb

Set wb = Workbooks.Open(Application.GetOpenFilename(«Файлы Excel,*.xls*», , «Выбор файла»))

‘Создаем в открытой книге новый лист и присваиваем ссылку на него переменной newws

Set newws = wb.Worksheets.Add

    With newws

        ‘Присваиваем имя новому листу: «Отчет от dd.mm.yyyy»

        .Name = «Отчет от « & Date

            ‘Запускаем цикл, перебирающий листы

            For Each ws In wb.Worksheets

                ‘Проверяем, что имя текущего листа не равно имени нового листа «Отчет…»

                If ws.Name <> newws.Name Then

                    ‘Копируем столбец «B» текущего листа на лист «Отчет…» в столбец n

                    ws.Columns(«B»).Copy Destination:=.Columns(n)

                    ‘Добавляем ячейку cверху столбца n

                    .Cells(1, n).Insert Shift:=xlShiftDown

                    ‘Записываем в добавленную ячейку имя текущего листа

                    .Cells(1, n) = ws.Name

                    ‘Задаем тексту в добавленной ячейке полужирное начертание

                    .Cells(1, n).Font.Bold = True

                    n = n + 1

                End If

            Next

    End With

End Sub

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


{quote}{login=Паша}{date=28.05.2010 04:46}{thema=}{post}Sub one()  

  Dim sh As Sheets  

  For Each sh In Workbook.Sheets  
If sh.Name <> «Сводная» Then  
Range(«A1:AK37»).Select  
   Selection.Copy  
   Sheets(«Ñâîäíàÿ»).Select  
   Range(«L28»).Select  
   ActiveSheet.Paste  
End If  
Next  
End Sub  

      сделал такой макрос который копирует всё в одно место что бы посмоотреть F8 как он вставляет попеременно всё, выдаёт ошибку Метод ор дата мембер нот фаунд и выделяет строку с IF. А если не прописывать Dim sh as shеet то выдаёт Object Required и выделяет первую строку For each…. И ещё к End приписал If так как выдаёт Next whithout For{/post}{/quote}  

  просто вы обявили не тот тип    

    sheets — это коллекция листов, а вам нужно тип элементов этой коллекции, но и тут может быть засада — объекта sheet не существует, а если использовать worksheet , то не все листы могут быть рабочими, встречаются меж ними и листы диаграмм, макросов и т.п. так что использование универсального обявления object в данном случае самое оно, но я к тому, что можно вообще не объявлять тип, тогда транслятор сам присвоит тип вариант, кот очень даже прокатит..

Ill show you how to loop through all of the worksheets in a workbook in Excel using VBA and Macros.

This only takes a few lines of code and is rather simple to use once you understand it.

Here is the macro that will loop through all worksheets in a workbook in Excel:

Sub Sheet_Loop()
'count the number of worksheets in the workbook
sheet_count = ActiveWorkbook.Worksheets.Count

'loop through the worksheets in the workbook
For a = 1 To sheet_count

    'code that you want to run on each sheet
    
    'simple message box that outputs the name of the sheet
    MsgBox ActiveWorkbook.Worksheets(a).Name

Next a
End Sub

Now, Ill go through the macro step-by-step.

ActiveWorkbook.Worksheets.Count

This line is what counts the number of worksheets that are in the workbook.

The first part of the line simply sets the variable sheet_count equal to the number of sheets in the workbook:

sheet_count = ActiveWorkbook.Worksheets.Count

Now that we know how many worksheets there are, we can loop through them.

We are going to use a very simple For Next loop in this case and you can copy it directly from here into your project.

For a = 1 To sheet_count
'code that you want to run on each sheet
Next a

In the above lines we are creating a new variable a and setting it equal to 1.  We then use the sheet_count variable to tell the macro when to stop looping; remember that it holds the numeric value of how many sheets there are in the workbook.

After this first line, which creates the loop, we then put all of the code that we want to run on each worksheet.

Dont forget that, at the end of the loop we still need something:

Next a

This tells the For loop that it should increment the value of the a variable by 1 each time the loop runs through a cycle or goes through a sheet.  The loop will not work without this line of code at the end of it.

In the original example we also have a line of code within the For loop:

MsgBox ActiveWorkbook.Worksheets(a).Name

This line will output the name of each worksheet into a pop-up message box; it also illustrates how you can access the worksheets from within the loop.

To do anything with the sheets from within the loop, we need to access each sheet by its reference or index number.  Each sheet has an index number and it always starts at 1 and increments by 1 for the next sheet in the workbook.

This is why we create the a variable and set it equal to 1 in the For loop, because the first sheet in the workbook always has an index number of 1, and we want to use a as the index number to access the worksheets.

Each time the loop runs and a is incremented by one, this allows you to access the next sheet in the workbook.  This is why we needed to count how many sheets were in the workbook, so we would know when to tell the For loop to stop running because there were no more sheets.

So, we can access the worksheets from within the loop by using
ActiveWorkbook.Worksheets(index number)

or

Sheets(index number)

Remember that the variable a is being used as our index number in this case.

Using this method you can do anything you want with the corresponding worksheet.

And thats how you loop through all worksheets in a workbook in Excel!

Make sure to download the accompanying file for this tutorial so you can see the VBA/Macro code in action.

Similar Content on TeachExcel

Get the Name of a Worksheet in Macros VBA in Excel

Tutorial: How to get the name of a worksheet in Excel using VBA and Macros and also how to store tha…

Excel Input Form with Macros and VBA

Tutorial:
Forms Course
How to make a data entry form in Excel using VBA and Macros — this allows yo…

Get User Submitted Data from a Prompt in Excel using VBA Macros

Tutorial: How to prompt a user for their input in Excel.
There is a simple way to do this using VBA …

Find the Next Blank Row with VBA Macros in Excel

Tutorial:
Learn how to find the next empty cell in a range in Excel using VBA and Macros.  This me…

Loop Through an Array in Excel VBA Macros

Tutorial:
I’ll show you how to loop through an array in VBA and macros in Excel.  This is a fairly…

Copy Data or Formatting to Multiple Worksheets in Excel

Tutorial:
Quickly copy all or parts of a single worksheet — data, formatting, or both — to multiple…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Понравилась статья? Поделить с друзьями:
  • Excel vba цикл row
  • Excel vba цикл for по ячейкам
  • Excel vba цикл for для массива
  • Excel vba цикл for exit
  • Excel vba цикл do loop