How to insert and run VBA code in Excel

Configurare noua (How To)

Situatie

Suppose you need to change your data in some way. You googled a lot and found a VBA macro that solves your task. However, your knowledge of VBA leaves much to be desired.

Solutie

Pasi de urmat
  • Open your workbook in Excel.
  • Press Alt + F11 to open Visual Basic Editor (VBE).

Excel Visual Basic Editor window

  • Right-click on your workbook name in the “Project-VBAProject” pane (at the top left corner of the editor window) and select Insert -> Module from the context menu.

Insert a new VBA module to the Excel workbook

  • Copy the VBA code (from a web-page etc.) and paste it to the right pane of the VBA editor (“Module1” window).

Paste the code to the VBA module

If the code of your VBA macro does not contain the following lines in the beginning:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Then add the following lines to get your macro to work faster (see the screenshots above):

  • To the very beginning of the code, after all code lines that start with Dim (if there are no “Dim” lines, then add them right after the Sub line):
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
  • To the very of the code, before End Sub:
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

These lines, as their names suggest, turn off screen refresh and recalculating the workbook’s formulas before running the macro. After the code is executed, everything is turned back on. As a result, the performance is increased from 10% to 500% (aha, the macro works 5 times faster if it continuously manipulates the cells’ contents).

Press Crl + S, then click the “No” button in the “The following features cannot be saved in macro-free workbook” warning dialog.

Tip solutie

Permanent

Voteaza

(2 din 5 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?