Не могу удалить модуль vba excel

Have you ever seen a text file in a notepad or a source code file in visual studio code? These all are just basic files where you can write some code or information. Similarly, we have modules in excel, each module has its code window, where you can write some code and allow it to automate your repetitive tasks. There can be multiple modules. We can create, rename or delete a module in just a few mouse clicks. In this article, we will learn how to create and delete a module in excel VBA. 

Module and its types

A module is a set of instructions written in a VBA editor. There are broadly 5 types of modules in VBA: 

  1. General-Purpose Module: It is the simplest type of module. If we record a macro that will get stored in a module. This is called a general-purpose module. We can simply write code in the VBA editor also.
  2. Workbook Module: Workbook module handles the events happening at a workbook level. For example, opening, closing or renaming a workbook.
  3. Worksheet Module: The worksheet module is driven by the events happening at the worksheet level. For example, activating a worksheet or flipping between different worksheets. Automating the task such as merging the worksheets. 
  4. Userform Module: Userform Module is a way to input a piece of information from the user.  It is one of the most useful tools of VBA. 
  5. Class Module: It’s similar to the classes in other languages. We create our objects. VBA has built-in objects such as the Collection, Workbook, etc. The inheritance in VBA is minimal and much more restricted than in other languages. 

Creating a VBA module

Following are the steps to create a VBA module,

Step 1: Go to Developer Tab, and select Visual Basic in the menu bar. 

Selecting-visual-basic

Step 2: A VBA editor appears. We can see the information on all the worksheets and workbooks in the editor tab. 

Workbook-and-worksheets

Step 3: Go to Insert Tab and select Module

Selecting-module

Step 4: A module name module1 is created.

Module-1-created

Deleting a VBA module

Following are the steps to delete a VBA module,

Step 1:  Given 3 modules name module1, module2, and module3. Delete module3 from the Modules. 

Deleting-module-3

Step 2: Right-click on module3 and click on Remove module3. A dialogue box appears. 

Removing-module

Step 3: The dialogue box tells whether you want to export the given module or not. If you, do not want to save the module on your PC, then click on No.

Dialogue-box

Step 4: Module3 has been deleted from the VBA editor. 

Module3-deleted

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

1. Откройте рабочую книгу Excel, в которую планируете импортировать модуль. Для импорта модуля в Личную книгу макросов, откройте любую книгу.

2. Откройте редактор VBA сочетанием клавиш Alt+F11 (в этом сочетании используется левая клавиша Alt). Обратите внимание на наличие в окне редактора VBA окна проводника «Project-VBAProject», обычно, расположенного слева. При отсутствии, отобразите его через главное меню, выбрав «View» — «Project Explorer».

3. В окне проводника «Project-VBAProject» найдите строку «VBAProject (ИмяКниги)», где «ИмяКниги» — это имя книги, в которую вы собираетесь импортировать модуль. Если вы желаете импортировать модуль в Личную книгу макросов, строка называется «VBAProject (PERSONAL.XLSB)». Если у вас нет Личной книги макросов — создайте ее.

4. У выбранной строки раскройте все крестики слева.

5. Откройте контекстное меню, кликнув правой кнопкой мыши на строке «ЭтаКнига», и выберите в нем пункт «Import File…».

6. В открывшемся окне выбора файла найдите импортируемый модуль с расширением .bas и дважды кликните по нему, или кликните один раз и нажмите кнопку «Открыть». Модуль импортирован и отобразился в проводнике под именем «Module» с очередным номером, независимо от имени импортируемого файла.

7. Если вы импортировали модуль в Книгу Excel 2007-2016 с расширением .xlsx, ее необходимо будет пересохранить как «Книга Excel с поддержкой макросов (.xlsm)», иначе импортированный модуль не сохранится.

Инструкцию с картинками вы можете посмотреть здесь в параграфе «Пользовательская функция «СуммаПрописью».

Экспорт модуля в редакторе VBA

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

2. Откройте редактор VBA сочетанием клавиш Alt+F11 и в окне проводника «Project-VBAProject» найдите экспортируемый модуль.

3. Откройте контекстное меню, кликнув правой кнопкой мыши на экспортируемом модуле, и выберите в нем пункт «Export File…».

4. В открывшемся окне выберите папку, куда следует сохранить экспортируемый модуль, если необходимо, измените название сохраняемого файла, и нажмите кнопку «Сохранить». Модуль экспортирован и отобразился в выбранном каталоге с указанным именем и расширением .bas.

Удаление модуля в редакторе VBA

1. В окне проводника «Project-VBAProject» найдите удаляемый модуль.

2. Откройте контекстное меню, кликнув правой кнопкой мыши на удаляемом модуле, и выберите в нем пункт «Remove Module…» с номером удаляемого модуля.

3. VBA Excel предложит экспортировать модуль перед удалением, нажмите «Да», если хотите сохранить модуль, или «Нет», чтобы удалить без сохранения.

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

Программный экспорт-импорт модуля

Пример программного экспорта стандартного модуля "Module1" из книги "Книга2.xlsm" и импорта его в книгу "Книга3.xlsm" с помощью кода VBA Excel:

Sub ExportImportModule()

    Workbooks(«Книга2.xlsm»).VBProject.VBComponents(«Module1»).Export «C:ТестоваяModule1.bas»

    Workbooks(«Книга3.xlsm»).VBProject.VBComponents.Import «C:ТестоваяModule1.bas»

End Sub

Если в книге "Книга3.xlsm" уже присутствует модуль с именем "Module1", то импортированному модулю будет присвоен другой номер.

Программное удаление модуля

Код VBA Excel для программного удаления стандартного модуля с именем "Module24":

Sub RemoveModule()

    With ThisWorkbook.VBProject

        .VBComponents.Remove .VBComponents(«Module24»)

    End With

End Sub

Замените имя "Module24" на имя своего модуля, который вы хотите безвозвратно удалить.


It’s complicated. See this link to learn more about why.

In short this is what you need to do:

First you need to reference VBIDE

VBIDE The VBIDE is the object library that defines all the objects and
values that make up VBProject and the Visual Basic Editor. You must
reference this library to use the VBA Extensibility objects. To add
this reference, open the VBA editor, open your VBProject in the
editor, and go to the Tools menu. There, choose References . In the
References dialog, scroll down to Microsoft Visual Basic for
Applications Extensibility 5.3 and check that item in the list. You
can add the reference programmatically with code like:

ThisWorkbook.VBProject.References.AddFromGuid _
    GUID:="{0002E157-0000-0000-C000-000000000046}", _
    Major:=5, Minor:=3

Next, you need to grant ‘Trust access to the Visual Basic Project’

Next, you need to enable programmatic access to the VBA Project. In
Excel 2003 and earlier, go the Tools menu (in Excel, not in the VBA
editor), choose Macros and then the Security item. In that dialog,
click on the Trusted Publishers tab and check the Trust access to the
Visual Basic Project setting.

In Excel 2007, click the Developer item on the main Ribbon and then
click the Macro Security item in the Code panel. In that dialog,
choose Macro Settings and check the Trust access to the VBA project
object model.


Now you can add the code to delete the module:

Deleting A Module From A Project

This code will delete Module1 from the VBProject. Note that you cannot
remove any of the Sheet modules or the ThisWorkbook module. In
general, you cannot delete a module whose Type is vbext_ct_Document.

Sub DeleteModule()
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent

    Set VBProj = ActiveWorkbook.VBProject
    Set VBComp = VBProj.VBComponents("Module1")
    VBProj.VBComponents.Remove VBComp
End Sub

Return to VBA Code Examples

In this Article

  • How to Rename or Delete a VBA module or Form
  • Renaming a Module
  • Delete a Module
    • Name Modules & Forms

How to Rename or Delete a VBA module or Form

The first time you insert a module in VBA, it will automatically be given the name of “Module1” and subsequent module will become Module2, Module3 etc. Similarly, when you insert a UserForm it will be called UserForm1, UserForm2 etc.

VBA 15 PIC 01

Renaming a Module

To rename your module or form, you need to have the properties window switched on in your VBE.

If the properties windows is not showing, press F4 or go to the menu bar and select View > Properties Window.

VBA 15 PIC 02

  1. Click on the module you wish to rename in the Project Explorer.
  2. Select the name property in the Properties Window (a module will only have this property; a form has multiple properties)VBA 15 PIC 03

3. Delete the module name (in this case Module1) and type in the name you want to call your module.

VBA 15 PIC 04

4. Press enter to rename the module.

VBA 15 PIC 05

You rename your forms in the same manner.

Delete a Module

Occasionally you may have the need to remove a module or form that you no longer need.

Right-click on the module or form you wish to remove to show the right click short cut menu.

VBA 15 PIC 06

Click Remove (in this case Module2)

OR

Click on the File menu, and then click on Remove (Module2).

VBA 15 PIC 07

A warning box will appear asking if you want to Export the module or form before you remove it. Exporting the module or form enables you to save it as an individual file for use in a different Excel project at some other time.

VBA 15 PIC 08

More often than not when you remove a module or form it is because you do not need it, so click No.

Name Modules & Forms

It is good practice to rename modules and forms in order to give them more meaningful names. For example, if UserForm1 is going to be a form for entering invoice details, we can rename it to frmInvoices.  Similarly, if Module1 is going to be used to hold some general functions that are going to be used repetitively throughout your code, you could rename it to basGeneral or modGeneral (depending on which naming conventions you like to use).

It is a good idea to be consistent with the naming conventions, both in naming your modules and forms, as well as the variables that you use within your code.  You will notice that I have written the first 3 letters of the module or form name in lowercase, and have a capital letter at the beginning of the description for the module or form.  This is known as CamelCase (https://en.wikipedia.org/wiki/Camel_case) and is a good habit to  get into when naming your objects. I have also used the Leszynski naming convention which is often used by Visual Basic programmers. (https://en.wikipedia.org/wiki/Leszynski_naming_convention).

VBA Coding Made Easy

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

Learn More!

При первой вставке модуля в VBA ему автоматически будет присвоено имя «Модуль1», А последующий модуль станет Module2, Module3 и т. Д. Аналогичным образом, когда вы вставляете пользовательскую форму, она будет называться UserForm1, UserForm2 и т. Д.

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

Чтобы переименовать модуль или форму, вам необходимо включить окно свойств в вашем VBE.

Если окна свойств не отображаются, нажмите F4 или перейдите в строку меню и выберите Вид, Характеристики Окно.

  1. Щелкните модуль, который хотите переименовать, в Обозреватель проекта.
  2. Выберите свойство name в Окно свойств (модуль будет иметь только это свойство; форма имеет несколько свойств)

3. Удалите имя модуля (в данном случае Module1) и введите имя, которое вы хотите назвать своим модулем.

4. Нажмите Enter, чтобы переименовать модуль.

Таким же образом вы переименовываете свои формы.

Удаление модуля

Иногда вам может потребоваться удалить модуль или форму, которые вам больше не нужны.

Щелкните правой кнопкой мыши модуль или форму, которые вы хотите удалить, чтобы отобразить контекстное меню, вызываемое правой кнопкой мыши.

Нажмите Удалять (в этом случае Модуль2)

ИЛИ

Нажать на Файл меню, а затем нажмите Удалите (Module2).

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

Чаще всего, когда вы удаляете модуль или форму, это происходит потому, что он вам не нужен, поэтому нажмите Нет.

Именование модулей и форм

Рекомендуется переименовывать модули и формы, чтобы дать им более понятные имена. Например, если UserForm1 будет формой для ввода сведений о счете, мы можем переименовать ее в frmInvoices. Точно так же, если Module1 будет использоваться для хранения некоторых общих функций, которые будут повторно использоваться в вашем коде, вы можете переименовать его в basGeneral или modGeneral (в зависимости от того, какие соглашения об именах вы хотите использовать).

Рекомендуется соблюдать соглашения об именах как при именовании ваших модулей и форм, так и переменных, которые вы используете в своем коде. Вы заметите, что я написал первые 3 буквы имени модуля или формы в нижнем регистре и поставил заглавную букву в начале описания модуля или формы. Это известно как CamelCase (https://en.wikipedia.org/wiki/Camel_case) и является хорошей привычкой при именовании объектов. Я также использовал соглашение об именах Лешинского, которое часто используется программистами Visual Basic. (https://en.wikipedia.org/wiki/Leszynski_naming_convention).

Вы поможете развитию сайта, поделившись страницей с друзьями

Понравилась статья? Поделить с друзьями:
  • Не могу удалить лист в книге excel
  • Не могу удалить лист в excel кнопка не активна
  • Не могу удалить колонтитулы в word 2010
  • Не могу удалить колонтитул в word
  • Не могу удалить картинку в word