How to insert and run VBA code in Excel - tutorial for beginners

This is a short step-by-step tutorial for beginners showing how to add VBA code (Visual Basic for Applications code) to your Excel workbook and run this macro to solve your spreadsheet tasks.

Most people like me and you are not real Microsoft Office gurus. So, we may not know all specificities of calling this or that option, and we cannot tell the difference between VBA execution speed in different Excel versions. We use Excel as a tool for processing our applied data.

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. Feel free to study this step-by-step guide to be able to use the code you found:

Insert VBA code to Excel Workbook

For this example, we are going to use a VBA macro to remove line breaks from the current worksheet.

  1. Open your workbook in Excel.
  2. Press Alt + F11 to open Visual Basic Editor (VBE).
    Excel Visual Basic Editor window
  3. 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
  4. 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

  5. Tip: Speed up macro execution

    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).

  6. Save your workbook as "Excel macro-enabled workbook".

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

    The "Save as" dialog will open. Choose "Excel macro-enabled workbook" from the "Save as type" drop-down list and click the Save button.
    Save your workbook as Excel macro-enabled workbook

  7. Press Alt + Q to close the Editor window and switch back to your workbook.

How to run VBA macros in Excel

When you want to run the VBA code that you added as described in the section above: press Alt+F8 to open the "Macro" dialog.

Then select the wanted macro from the "Macro Name" list and click the "Run" button.
Press Alt+F8 to run the VBA macro

256 comments

  1. Hi,

    I need a code to color the sheet tab to red if T43 in that sheet is > 0, no change to sheet color for all other cases. I'd like this to run for the entire workbook of 160 sheets automatically. Can someone help?

    Thank you.

    Alice

    • i like your question as well.
      Can someone help us on this?

  2. please can I have a cod to calculate the average for each 29 number of excel column with 184450 row

  3. Hello everyone, I would like to ask you for help with my problem. I think it's possible to solve it with VBA, but I'm not sure how to do it. Also, if there is a way to do it without VBA, even better.
    I exported the tasks from the Planner to Excel (did some work to filter and format the data I needed, etc.) and finally, I have a list of tasks that belong to a person. For each person, I have to manually enter the approximate time needed to complete the task, during the task that person should enter each week how many hours he spends solving the task and when the task is completed I can compare in the table the time he spends and the time I set for this assignment. This table needs to be used for a long time, and the task list changes almost every week, so I need to export new data from the scheduler every week, but save the data previously entered for some tasks. Each time an export is performed, the order of tasks in Excel changes and this is the point when a problem occurs. The time I need to specify for each task (forecast) is entered manually, for example, for the task "Task1" in A1 the forecast is entered in C1. The next time I export tasks from the Planner, it is possible that "Task 1" will no longer be in A1 (ie I added another task in the Planner and now that task is the first, so "Task 1" moves to A2), but the forecast for " Task 1 "remained in C1 (because column C is not included in exports). How to ensure that cell C1 follows the task in A1, no matter where the data from A1 is transferred? In this case, when a new export is made, the forecast from C1 should be automatically moved to C2, because the task from A1 is now to A2. I hope someone can help me. Thanks in advance, Los

  4. I Want use VBA code flash data on return on blog

  5. Hello, thank you for your help. If possible, could you please help me with an additional problem? I have around 1000+ xml files and I want to convert them to excel or csv file. Is it possible to do that as well? If so, can you show me how?

    Thank you for your time.

  6. Hey! I am looking for a little help with a code. I am a beginner it is a little confusing..

    Change the application so that now there is no limit.

    For EG, if the strategy says to buy 30% more shares but there is not enough cash on hand to do so, the investor will now borrow the cash they need. Now the cash positions in
    columns H and J of the Model worksheet can be negative, indicating that the investor
    owes money to the lender.

    Capture the maximum the investor ever owes during the year in an extra output cell, keep
    track of it, and summarize it (including a histogram), just like all of the other outputs,
    with your VBA code.

  7. Hi Sir i want to count diffent names in coloum wise what is the formula or code?

  8. i am new vb in excel and need some assistance with the following macro. any help greatly appreciated. i need to create a macro which will take value from sheet 1 cell A1 value ,(example: CD-600500 is available in sheet 1 cell A1) then increment the value by 1 in sheet 2 cell range A5:A50,also A5:A50 if the cell is blank try goto next row and increment the value by 1.

  9. I need a code to convert half of my numbers to variables. example if the number is 12345, i need to convert it as ABC45. (A=1, B=2 Etc..) Someone Please help.

  10. hi there, im quite new at programming but uses excel alot so what im looking for would help me quite alot.
    i would like to create a macro or a button that takes the value i a cell and multiplies it with negative one.
    Example:
    i have multiple sheets and plots in a number from sheet one to sheet two, then in sheet two i need the number to be multiplied with negative one, whilst still being traceble to where the value came from. is this possible?

    sorry if the explenation is bad, English is my second language.

  11. Hi sir thanks for sharing the info., my question is after saving the macro and its respective workbook if I want to run the same macro in other workbook will it work because i have tried it in the other workbook but it has not worked in other workbook or if I open the new excel sheet.

  12. hi... i need a vba code for making my worksheet for attendance system where after entering the time of went and out the people cannot edit except the user coder by keeping their password system or any method..

    • Hi Bibek,
      I can help you with that.
      What I understood you want to keep a record of employees attendance and once entered it cannot be edited without a password. correct?

    • Option Explicit

      Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
      Private Declare Function capCreateCaptureWindowA Lib "user32" (ByVal lpszWindowName As String, ByVal dwStyle As Long, ByVal X As Long, ByVal Y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hwndParent As Long, ByVal nID As Long) As Long
      Private Declare Function SendMessageA Lib "user32" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
      Private Declare Function DestroyWindow Lib "user32" (ByVal hndw As Long) As Boolean

      Private Const WM_CAP_DRIVER_CONNECT As Long = &H40A
      Private Const WM_CAP_DRIVER_DISCONNECT As Long = &H40B
      Private Const WM_CAP_EDIT_COPY As Long = &H41E
      Private Const WM_CAP_SET_PREVIEW As Long = &H432
      Private Const WM_CAP_SET_PREVIEWRATE As Long = &H434
      Private Const WM_CAP_SET_SCALE As Long = &H435
      Private Const WS_CHILD As Long = &H40000000
      Private Const WS_VISIBLE As Long = &H10000000
      Private Const SWP_NOMOVE As Long = &H2
      Private Const SWP_NOSIZE As Long = &H1
      Private Const HWND_BOTTOM As Long = 1

      Private CameraHandle As Long
      Private TargetCell As Range

      Private Sub Worksheet_Change(ByVal Target As Range)
      ' Check if the change occurred in the active cell
      If Target.Address = ActiveCell.Address Then
      ' Save the neighboring cell to paste the photo later
      Set TargetCell = ActiveCell.Offset(0, 1)

      ' Open the web camera and capture a photo
      CapturePhoto
      End If
      End Sub

      Private Sub CapturePhoto()
      ' Open the web camera
      CameraHandle = capCreateCaptureWindowA("Camera", WS_VISIBLE Or WS_CHILD, 0, 0, 640, 480, Me.Parent.hwnd, 0)
      If CameraHandle 0 Then
      SendMessageA CameraHandle, WM_CAP_DRIVER_CONNECT, 0, 0
      SendMessageA CameraHandle, WM_CAP_SET_PREVIEWRATE, 66, 0 ' Set the preview rate (milliseconds per frame)
      SendMessageA CameraHandle, WM_CAP_SET_PREVIEW, True, 0
      Sleep 2000 ' Wait for 2 seconds to stabilize the camera (adjust this value as needed)

      ' Capture the photo (copy it to the clipboard)
      SendMessageA CameraHandle, WM_CAP_EDIT_COPY, 0, 0

      ' Disconnect and destroy the camera window
      SendMessageA CameraHandle, WM_CAP_DRIVER_DISCONNECT, 0, 0
      DestroyWindow CameraHandle

      ' Paste the captured photo into the neighboring cell
      TargetCell.Select
      ActiveSheet.PasteSpecial Format:="Bitmap"
      Else
      MsgBox "Failed to access the web camera."
      End If
      End Sub
      how run this code

  13. Hi everyone I have a small problem with a vba to create with excel.
    I state that I can not create vba, but I was looking for information with which to be able to create it. I hope you can help me ,I would be really grateful.

    I expose the problem:

    I would like to enter a formula that:

    The moment I enter a particular name in one cell, other names that I decide, appear in other cells. It's possible to do it?

    • @Ezio,
      yes its possible. using Vlookup. but if you can explain a bit, i will be able to help.

  14. The code I copied from sount and sum cells by colour does not show up in the Macros name list after I have done the steps.

  15. I want a coding that use in ms excell for spellnumber formula

    Those convert a no in to write text

  16. Sir/Madam, I am an excel user. I am facing a problem. Here is a vendor who gives services various pathological test;like TC,DC,ESR. T3,T4,TSH.LFT etc.I want to create a database file in Sheet1 and where these tests are kept. Now day by day there so many patients examine their various patho.tests. I want to create that type of database when I write the test name the machine invoke the respective test and rate and put the value againt that particular patient. How can I solve the problem? Awaiting for your positive reply.

  17. Can anyone please help me....... My requirement is i have an a master sheet having 5000 rows and 5 to 6 columns.... In that sheet i will give you one column data in another sheet automatically remaining column wil fill...is it possible

  18. Hi,
    i have a query with regard macro.
    Function timestamp(Reference As Range)
    If Reference.Value “” Then
    timestamp = Format(Now, “dd-mmm-yy hh:mm:ss”)
    Else
    Ok = “”
    End If
    End Function

    this code show text format show date but i want date format please help me.

  19. Hi!
    Thank you! It saved me about a weeks worth of copy-paste with notepad in between to go through around 15000 lines. Awsome!

  20. Hi

    How can I write a code to do the following; If content in( W3:W395) is blank then delete the content in cell (G3:G395).

    Please help.

Post a comment



Thank you for your comment!
When posting a question, please be very clear and concise. This will help us provide a quick and relevant solution to
your query. We cannot guarantee that we will answer every question, but we'll do our best :)