Vba and excel and move

Содержание

  1. Метод Sheets.Move (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Sheets.Move method (Excel)
  8. Syntax
  9. Parameters
  10. Remarks
  11. Example
  12. Support and feedback
  13. Метод Worksheets.Move (Excel)
  14. Синтаксис
  15. Параметры
  16. Замечания
  17. Пример
  18. Поддержка и обратная связь
  19. Worksheet.Move method (Excel)
  20. Syntax
  21. Parameters
  22. Remarks
  23. Example
  24. Support and feedback
  25. Метод Worksheet.Move (Excel)
  26. Синтаксис
  27. Параметры
  28. Замечания
  29. Пример
  30. Поддержка и обратная связь

Метод Sheets.Move (Excel)

Перемещает лист в другое место в книге.

Синтаксис

expression. Переместить (до, после)

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

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Лист, перед которым будет размещен перемещенный лист. Невозможно указать параметр Before , если указать After.
After Необязательный Variant Лист, после которого будет размещен перемещенный лист. Вы не можете указать After , если укажем значение До.

Замечания

Если не указать параметр «До» или «После», Microsoft Excel создает новую книгу, содержащую перемещенный лист.

Пример

В этом примере лист 1 перемещается после Листа 3 в активной книге.

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

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

Источник

Sheets.Move method (Excel)

Moves the sheet to another location in the workbook.

Syntax

expression.Move (Before, After)

expression A variable that represents a Sheets object.

Parameters

Name Required/Optional Data type Description
Before Optional Variant The sheet before which the moved sheet will be placed. You cannot specify Before if you specify After.
After Optional Variant The sheet after which the moved sheet will be placed. You cannot specify After if you specify Before.

If you don’t specify either Before or After, Microsoft Excel creates a new workbook that contains the moved sheet.

Example

This example moves Sheet1 after Sheet3 in the active workbook.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Worksheets.Move (Excel)

Перемещает лист в другое место в книге.

Синтаксис

expression. Переместить (до, после)

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

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Лист, перед которым будет размещен перемещенный лист. Невозможно указать параметр Before , если указать After.
After Необязательный Variant Лист, после которого будет размещен перемещенный лист. Вы не можете указать After , если укажем значение До.

Замечания

Если не указать параметр «До» или «После», Microsoft Excel создает новую книгу, содержащую перемещенный лист.

Пример

В этом примере лист 1 перемещается после Листа 3 в активной книге.

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

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

Источник

Worksheet.Move method (Excel)

Moves the sheet to another location in the workbook.

Syntax

expression.Move (Before, After)

expression A variable that represents a Worksheet object.

Parameters

Name Required/Optional Data type Description
Before Optional Variant The sheet before which the moved sheet will be placed. You cannot specify Before if you specify After.
After Optional Variant The sheet after which the moved sheet will be placed. You cannot specify After if you specify Before.

If you don’t specify either Before or After, Microsoft Excel creates a new workbook that contains the moved sheet.

Example

This example moves Sheet1 after Sheet3 in the active workbook.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Worksheet.Move (Excel)

Перемещает лист в другое место в книге.

Синтаксис

expression. Переместить (до, после)

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

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Лист, перед которым будет размещен перемещенный лист. Невозможно указать параметр Before , если указать After.
After Необязательный Variant Лист, после которого будет размещен перемещенный лист. Вы не можете указать After , если укажем значение До.

Замечания

Если не указать параметр «До» или «После», Microsoft Excel создает новую книгу, содержащую перемещенный лист.

Пример

В этом примере лист 1 перемещается после Листа 3 в активной книге.

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

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

Источник

Skip to content

Move Method of Worksheet Object VBA

  • VBA Move Method Excel Worksheet Object

Move worksheet method in VBA is used to move the worksheet from one location to another location in the same workbook or another new workbook or existing workbook.

VBA Move Method Excel Worksheet Object

  • Why we use Move Worksheet Method in VBA?
  • VBA Move Worksheet Method: Syntax
  • VBA Move Worksheet Method: Before
  • VBA Move Worksheet: After
  • VBA Move Worksheet Method: Instructions

Why we use Move Worksheet Method in VBA?

If we want to move worksheet from one workbook to another existing workbook or new workbook we will use Move method of worksheet object. Sometimes we may want to move worksheet in the active workbook at the beginning of the worksheet or in between worksheets or at the end of worksheet. Need basis we can move the worksheets using Move worksheet method in VBA.

VBA Move Worksheet Method: Syntax

Here is the syntax to Move Worksheet using VBA.

Sheets(“Worksheet Number”).Move(

[Before], [After])

Where
Before: It’s an Optional parameter. The worksheet will be moved to before the specified worksheet. Then we can’t specify after parameter.
After: It’s an Optional parameter. The worksheet will be moved to after the specified worksheet. Then we can’t specify after parameter.
Note: If you don’t specify either before or after, Excel will create new workbook that contains the moved worksheet.

VBA Move Worksheet Method: Before

Please find the below example, It will show you how to Move the Worksheet to the beginning.

Sub MoveSheet_Beginning()
    Worksheets("Sheet3").Move Before:=Worksheets(1)
End Sub

In the above example we are moving the Worksheet named ‘Sheet3’ to the beginning of the worksheet. Where ‘1’ represents the Worksheet index number (Nothing but first available sheet in the workbook).

Sub MoveSheet_Beginning1()
    ActiveSheet.Move Before:=Worksheets(1)
End Sub

In the above example we are moving the active worksheet to the beginning of the worksheet.

VBA Move Worksheet Method: After

Please find the below example, It will show you how to Move the Worksheet at the end of the available worksheets.

Sub MoveSheet_End()
    Worksheets("Sheet3").Move After:=Worksheets(Worksheets.Count)
End Sub

In the above example we are moving the Worksheet named ‘Sheet3’ to the end of the worksheet. Where ‘Worksheets.Count’ represents the number of available worksheets in the workbook

Sub MoveSheet_End()
    ActiveSheet.Move After:=Worksheets(Worksheets.Count)
End Sub

In the above example we are moving the active worksheet to the end of the worksheet.

VBA Move Worksheet Method: Instructions

Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:

  1. Open an Excel Worksheet
  2. Press Alt+F11 :This will Open the VBA Editor. Otherwise, you can open it from the Developer Tab
  3. Insert a Module from Insert Menu
  4. Copy the above code for activating worksheet and Paste in the code window(VBA Editor)
  5. Save the file as macro enabled Worksheet
  6. Press ‘F5’ to run it or Keep Pressing ‘F8’ to debug the code line by line and check how the Worksheet is Moving.
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates
      • In this topic:
  • Why we use Move Worksheet Method in VBA?
  • VBA Move Worksheet Method: Syntax
  • VBA Move Worksheet Method: Before
  • VBA Move Worksheet Method: After
  • VBA Move Worksheet Method: Instructions

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
By PNRaoLast Updated: March 2, 2023

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Создание, копирование, перемещение и удаление рабочих листов Excel с помощью кода VBA. Методы Sheets.Add, Worksheet.Copy, Worksheet.Move и Worksheet.Delete.

Создание новых листов

Создание новых рабочих листов осуществляется с помощью метода Sheets.Add.

Синтаксис метода Sheets.Add

expression.Add [Before, After, Count, Type]

где expression — переменная, представляющая собой объект Sheet.

Компоненты метода Sheets.Add

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлен новый.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлен новый.
  • Count — необязательный параметр типа данных Variant, указывающий, сколько листов будет добавлено (по умолчанию — 1).
  • Type — необязательный параметр типа данных Variant, указывающий тип листа: xlWorksheet** (рабочий лист) или xlChart (диаграмма), по умолчанию — xlWorksheet.

*Если Before и After не указаны, новый лист, по умолчанию, будет добавлен перед активным листом.

**Для создания рабочего листа (xlWorksheet) можно использовать метод Worksheets.Add, который для создания диаграмм уже не подойдет.

Примеры создания листов

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

‘Создание рабочего листа:

Sheets.Add

Worksheets.Add

ThisWorkbook.Sheets.Add After:=ActiveSheet, Count:=2

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Лист1

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(1)

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(«Лист1»)

‘Создание нового листа с заданным именем:

Workbooks(«Книга1.xlsm»).Sheets.Add.Name = «Мой новый лист»

‘Создание диаграммы:

Sheets.Add Type:=xlChart

‘Добавление нового листа перед

‘последним листом рабочей книги

Sheets.Add Before:=Sheets(Sheets.Count)

‘Добавление нового листа в конец

Sheets.Add After:=Sheets(Sheets.Count)

  • Лист1 в After:=Лист1 — это уникальное имя листа, указанное в проводнике редактора VBA без скобок.
  • Лист1 в After:=Worksheets(«Лист1») — это имя на ярлыке листа, указанное в проводнике редактора VBA в скобках.

Создаваемый лист можно присвоить объектной переменной:

Dim myList As Object

‘В активной книге

Set myList = Worksheets.Add

‘В книге «Книга1.xlsm»

Set myList = Workbooks(«Книга1.xlsm»).Worksheets.Add

‘Работаем с переменной

myList.Name = «Listok1»

myList.Cells(1, 1) = myList.Name

‘Очищаем переменную

Set myList = Nothing

Если создаваемый лист присваивается объектной переменной, он будет помещен перед активным листом. Указать дополнительные параметры невозможно.

Копирование листов

Копирование рабочих листов осуществляется с помощью метода Worksheet.Copy.

Синтаксис метода Worksheet.Copy

expression.Copy [Before, After]

где expression — переменная, представляющая собой объект Worksheet.

Компоненты метода Worksheet.Copy

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлена копия.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлена копия.

*Если Before и After не указаны, Excel создаст новую книгу и поместит копию листа в нее. Если скопированный лист содержит код в проекте VBA (в модуле листа), он тоже будет перенесен в новую книгу.

Примеры копирования листов

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

‘В пределах активной книги

‘(уникальные имена листов)

Лист1.Copy After:=Лист2

‘В пределах активной книги

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

Worksheets(«Лист1»).Copy Before:=Worksheets(«Лист2»)

‘Вставить копию в конец

Лист1.Copy After:=Sheets(Sheets.Count)

‘Из одной книги в другую

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Copy _

After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1»)

‘Один лист активной книги в новую книгу

Лист1.Copy

‘Несколько листов активной книги в новую книгу*

Sheets(Array(«Лист1», «Лист2», «Лист3»)).Copy

‘Все листы книги с кодом в новую книгу

ThisWorkbook.Worksheets.Copy

* Если при копировании в новую книгу нескольких листов хотя бы один лист содержит умную таблицу — копирование невозможно. Один лист, содержащий умную таблицу, копируется в новую книгу без проблем.

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Перемещение листов

Перемещение рабочих листов осуществляется с помощью метода Worksheet.Move.

Синтаксис метода Worksheet.Move

expression.Move [Before, After]

где expression — переменная, представляющая собой объект Worksheet.

Компоненты метода Worksheet.Move

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет размещен перемещаемый лист.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет размещен перемещаемый лист.

*Если Before и After не указаны, Excel создаст новую книгу и переместит лист в нее.

Примеры перемещения листов

Простые примеры перемещения листов:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

‘В пределах активной книги

‘(уникальные имена листов)

Лист1.Move After:=Лист2

‘В пределах активной книги

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

Worksheets(«Лист1»).Move Before:=Worksheets(«Лист2»)

‘Размещение после последнего листа:

Лист1.Move After:=Sheets(Sheets.Count)

‘Из одной книги в другую

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Move _

After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1»)

‘В новую книгу

Лист1.Move

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Перемещение листа «Лист4» в позицию перед листом, указанным как по порядковому номеру, так и по имени ярлыка:

Sub Peremeshcheniye()

Dim x

x = InputBox(«Введите имя или номер листа», «Перемещение листа «Лист4»»)

If IsNumeric(x) Then x = CLng(x)

Sheets(«Лист4»).Move Before:=Sheets(x)

End Sub

Удаление листов

Удаление рабочих листов осуществляется с помощью метода Worksheet.Delete

Синтаксис метода Worksheet.Delete

expression.Delete

где expression — переменная, представляющая собой объект Worksheet.

Примеры удаления листов

‘По уникальному имени

Лист1.Delete

‘По имени на ярлычке

Worksheets(«Лист1»).Delete

‘По индексу листа

Worksheets(1).Delete

‘В другой книге

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Delete

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

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

You can copy and move a sheet in Excel using a VBA code, and in this tutorial, we will learn different ways to do that.

Copy a Sheet within the Same Workbook

If you want to copy a sheet within the same workbook, you can use the following code where you have used the copy method.

Sheets("Sheet5").Copy Before:=Sheets(1)

In this code, sheet1 is the first sheet in the workbook, and when you run this code, it copies the sheet with the name “Sheet5” before the first sheet in the workbook.

And if you want to copy it after the first sheet then the code would be like the following.

Sheets("Sheet5").Copy After:=Sheets(1)

And if you want to copy it after the first sheet, then the code would be like the following.

Sheets("Sheet5").Copy Before:=Sheets("Sheet3")
Sheets("Sheet5").Copy After:=Sheets("Sheet3")

When you run this VBA code, it copies the “Sheet5” before and after the “Sheet3”.

With the following line of code, you can copy a sheet after the last sheet in the workbook. It uses the sheet.count to get the count of the sheets and then uses the number to copy the sheet to the last.

Sheets("myNewSheet").Move After:=Sheets(Sheets.Count)

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Copy a Sheet in the Same Workbook with New Name

And if you want to copy a sheet and then want to rename it instantly, you need to use the name property, just like the following code.

Sheets("Sheet5").Move Before:=Sheets(1)
ActiveSheet.Name = "myNewSheet"

Move a Sheet within the Same Workbook

To move a sheet in the same workbook you need to use the move method as you have in the following code.

Sheets("Sheet5").Move After:=Sheets(1)

This code will move the “Sheet5” before the “Sheet2” as you can see in the above snapshot.

Copy a Sheet to the New Workbook

When you use the copy method without defining any sheet in the current workbook, VBA opens a new workbook and copy that sheet to that workbook.

Sheets("Sheet5").Copy

And to move a sheet to a new workbook.

Sheets("Sheet5").Move

Copy Multiple Sheets to the New Workbook

If you want to add multiple sheets to the new workbook in one go then use code like the following.

Sheets(Array("Sheet2", "Sheet3", "Sheet4", "Sheet5")).Copy

The above code creates an array of the sheets and then copy all of them to a new workbook.

Copy a Sheet to the Another Workbook

If you want to copy a sheet to another workbook that is already open then you can mention the workbook name after or before the argument.

Sheets("Sheet1").Copy Before:=Workbooks("Book1.xlsx").Sheets(1)

The above code copies the Sheet1 from the active workbook and adds to the before the first sheet of the Book1.xlsx that is already open.

 And if you want to move it.

Sheets("Sheet1").Move Before:=Workbooks("Book1.xlsx").Sheets(1)

Copy a Sheet to a Closed Workbook

There’s a way that you can copy a sheet to a workbook that is closed and you don’t need to open it. Look at the below code.

Sub vba_copy_sheet()
Dim mybook As Workbook

Application.ScreenUpdating = False

Set mybook = _
Workbooks.Open _
("C:UsersDellDesktopsamplefile.xlsx")

Workbooks("Book1.xlsx").Sheets("Sheet2").Copy Before:=mybook.Sheets(1)
mybook.Close SaveChanges:=True

Application.ScreenUpdating = True

End Sub

In this code, you have the myBook variable and then a workbook assigned to it. We have turned off the screen updating so that code can perform the task at the backend.

Copy Sheet from Another Workbook without Opening it

In the same way, you can copy and move a sheet from a closed workbook. Look at the below code.

Sub vba_copy_sheet()
Dim mybook As Workbook

Application.ScreenUpdating = False

Set mybook = _
Workbooks.Open _
("C:UsersDellDesktopsamplefile.xlsx")

mybook.Sheets("mySheet").Copy Before:=Workbooks("Book1.xlsx").Sheets(1)
mybook.Close SaveChanges:=True

Application.ScreenUpdating = True
End Sub

More Tutorials on VBA Worksheets

  • Back to VBA Worksheet / VBA Tutorial

Automating processes with VBA can involve copying, moving, deleting and managing lots of files.  Thankfully, VBA has many built-in functions to undertake these tasks for us.  These files do not necessarily need to be Excel workbooks; they can be any file type.

Download the example file

I recommend you download the example file for this post.  Then you’ll be able to work along with examples and see the solution in action, plus the file will be useful for future reference.

Download Icon
Download the file: 0041 VBA copy, move, delete and manage files.zip

Check if a file exists

If any actions are performed on a file that does not exist, the VBA code will error.  As a result, checking for a file’s existence can be one of the most common action we perform.

The code below will display True or False in a message box to indicate if the file exists.

Sub CheckIfFileExists()

'Check if a file exists
MsgBox Dir("C:UsersmarksDocumentsFolderText.xlsx") <> ""

End Sub

The code below uses an If statement to carry out different actions depending on if the file does or does not exist.

Sub PerformActionIfFileExists()

Dim filePath As String

filePath = "C:UsersmarksDocumentsFolderFileName.xlsx"

If Dir(filePath) <> "" Then

    'Insert action for if the file exists
    'This example displays a message box
    MsgBox filePath & " exists."

Else

    'Insert actions if the file does not exist
    'This example displays a message box
    MsgBox filePath & " does not exist."

End If

End Sub

When regularly checking for the existence of files, it can be easier to have a reusable function within a Module to be called upon when required.

'Reusable function to check if a file exists
Function DoesFileExist(filePath) As Boolean

DoesFileExist = Dir(filePath) <> ""

End Function

The code below shows how to call the reusable function as part of an If statement.

Sub UseTheFunction()

Dim myFile As String

myFile = "C:UsersmarksDocumentsFolderFileName.xlsx"

'Call the reusable function to check for file existence
If DoesFileExist(myFile) = True Then

    'Insert action for if the file exists
    'This example displays a message box
    MsgBox "The file exists."

End If

End Sub

Rename a file

The code below renames a file.

Sub RenameAFile()

'Rename a file
Name "C:UsersmarksDocumentsFolderCurrentFileName.xlsx" _
    As "C:UsersmarksDocumentsFolderNewFileName.xlsx"

End Sub

If the target filename is already an existing file, the code will error.  Therefore, it is good practice to check if the source and target file names are already in use.

Check out this post for more examples of using VBA to rename files.

Moving a file

The code to move a file is the same syntax as the code to rename a file.

Sub MoveAFile()

'Move a file
Name "C:UsersmarksDocumentsFileName.xlsx" As _
    "C:UsersmarksDocumentsNew FolderFileName.xlsx"

End Sub

Copying a file

Copying a file retains the existing file, but creates a duplicate version of it in a new location.

Sub CopyAFile()

'Copy a file
FileCopy "C:UsersmarksDocumentsFolderOriginal File.xlsx", _
    "C:UsersmarksDocumentsNew FolderCopied File.xlsx"

End Sub

If the target filename is already an existing file, the code will error.  Therefore, it is good practice to check if the source and target file names are already in use.

Deleting files removes them completely.  Files deleted using VBA are not sent to the recycle bin, and since there is no undo functionality it can be quite dangerous.  Take extra care to ensure the code does what you expect it to.

The following code deletes a specific file.

Sub DeleteSpecificFile()

'Delete a specific file
Kill "C:UsersmarksDocumentsFolderDeleteMe.xlsx"

End Sub

The code below deletes files using a wildcard.  In this circumstance, it deletes all files with a .xlsx file extension.

Sub DeleteFilesWithWildcards()

'Delete all .xlsx files using the * wildcard character
Kill "C:UsersmarksDocumentsFolder*.xlsx"

End Sub

The example below deletes all the files in a folder by using wildcard characters.

Sub DeleteAllFilesInFolder()

'Delete all files from a folder using two * wildcard characters
Kill "C:UsersmarksDocumentsFolder*.*"

End Sub

Common wildcard characters are:

Character Description
* (asterisk) Any number of characters
? (question mark) Any individual characters

The example below applies the * (asterisk) and ? (question mark) wildcard characters

'Delete all .xlsx or .xlsm files from a folder, but not .xls files
'as the ? wildcard must be atleast on character in length
 Kill "C:UsersmarksDocumentsFolder*.xls?"

Get file attributes

Each files has specific attributes, for example, they can be read-only, hidden or system files etc..

The code below checks if a file is read-only.

Sub GetFileAttributes()

Dim myFile As String

myFile = "C:UsersmarksDocumentsFolderReadOnlyFile.xlsx"

'If the file is Read-Only, display message box
If (GetAttr(myFile) And vbReadOnly) <> 0 Then

    MsgBox "The file is Read only"

End If

End Sub

To check for other attributes, replace vbReadOnly in the code above with the required settings.

VBA Name of attribute Enumerator Description
vbNormal 0 Files with no attributes (default setting)
vbReadOnly 1 Read-only files
vbHidden 2 Hidden files
vbSystem 4 System files
vbVolume 8 Volume label
vbDirectory 16 Directories

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Понравилась статья? Поделить с друзьями:
  • Vba excel activecell что это
  • Vba and excel and count rows
  • Vba excel activecell свойства
  • Vba and excel 2016
  • Vba excel active cell