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 Excel 2019, 2016, 2013 and 2010. 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

You may also be interested in

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

  1. Hemanth Kumar C says:


    I required a VBA Code for Updating a Bulk excel into a Application(Oracle) Data batabase & to Execute the same through the excel to Application.

    Ex :- The Complaint is to be closed in the system for this there are 4 Columns 2 are of Drop down & 1 is of Text field to Update a Remark, & in the 4th Column Present Date & Time will be appearing that has to remain Same.

    Hemanth C

  2. syed says:

    Hello There,

    Iam not able to click on module,i can see it but not able to click, can anyone help on this.


    • Alexander says:

      Sorry, I do not exactly understand the problem. Can you please send me a screenshot at

      • Muhammad Danish says:

        Sir i want to highlight the entire cell in excel..for this purpose i use the VBN and but in vbn when i open the module the dialog box show empty but in one video i saw when click on module open the detail.but i cant saw this wording can u help me?

  3. Jim says:

    Do you have any idea why some VBA code that works fine in Excel 2010 would lead to a "Microsoft Excel has stopped working" error in Excel 2013?



  4. Jim says:

    Thanks for the reply. Any suggestions for why that macro may not work in 2013?

  5. Angel says:

    when I copy and paste the formula (the one found in how to count by color and sum by color in an exel worksheet tutorial)into the module of my worksheet - it does not look the same. the letters are red and instead of line by line - it looks like it was a continuous formula (actually took up only 2 lines)

    so anyways - i tried to run it (alt8) and it is black - it seems like it does not recognize the formula I pasted.

    so I cut and pasted the formula into word document - and it took a few pages - and when I cut and copied it from there - it showed a solid line where the I copied onto the next page)

    any suggestions? am I doing some thing wrong?

  6. Angel says:

    I have cut/paste the formula once again in MS Word and then from there - copy/paste into module. It now shows up normal (rather than the 2 red lines of words in my previous post)

    so, now that its there...
    1. I saved the workbook as excel macro-enabled workbook
    2. Clicked ALT Q - to go back to my workbook
    3. I then ALT F8 to run it - but there is nothing there... blank....

    what am I missing? At this point - do I run the macro BEFORE I try to do what I want accomplished (uie: add sum of each yellow cell)?
    I think I am missing a step here. Your tutorial seems pretty well explained. I was very pleased and thought I understood it.... but I feel like Im missing a step somewhere....
    Thank you for your help.

  7. Robert says:

    I may be missing something, but even after pasting some code in, there is no macro listed when I use Alt+F8 - the window is blank.

    What step did I miss (that is not listed on this page?)

    • Alexander says:

      Hi Robert,
      I described all the needed steps in the article. Please make sure that the code you pasted contains the part beginning with Sub MacroName and ending with End Sub.

      • Cory says:

        I get an error when I put that in there.
        "Compile error:
        Expected: line number or label or statement or end of statement"

  8. Help says:

    I need help badly, I need macro-excel where:
    1) multiple rows of surnames in one column and firstnames in another column
    2) have to copy each name surname and first name to be pasted website asking for each in separate webpage boxes
    3) then I have to copy the printscreen result to another worksheet and resume to another row (new firstname and surname)
    Need a as this is a big project but few people/time
    Thanks, Alexander!

  9. Kumarapush says:

    Hai Alexander, I know bit of Macro, but the below lines are new to me.
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Very Interesting to know about this TIP, that it will increase the execution to a great extend. Thanks for the Info. :-)

  10. How to create a macro says:


    I prepare a report everyday, can it not be done with the help of macro.
    I downlaoad the raw report it from my client system and then format it and I use some simple formulae like sum, vlook up.

    Everyday the raw date keeps changing.

    please suggest at the earliest, how this can be done.


  11. parvin says:

    Hi, I want to link some pdf file data to excel using macro.Is it possible?

  12. sanjeev says:

    I am sanjeev .I am new in could u plzzzzzzzzz help me to sove my problem????????

    I write ,i code in VBA in excel...........
    to move from one sheet to onther by active x control command button.

    command button in first sheet1............


    it this i can go ,into second sheet.
    but as i close my sheet ,and reopen it ,it not works...........(means code disappears).

  13. karoline says:

    Thank you, thank you, thank you.

  14. Dheeraj says:

    hi, i am Dheeraj i am new in excel so i have some Question that how add any formula in micro in excel and how to treat excel as like my sql

    • Alexander says:

      Hello Dheeraj,

      You are asking very generic questions that do not directly relate to the topic covered in this article. I would advise you to find some good book on Excel or online tutorials that are plenty on the web.

  15. Anonymous says:

    Great post thanks for help me out!

  16. tere says:

    Hi, my data is about shift schedules, when i run my macro, it does read the shift schedule except that it doesnt count the days (per day, like monday -sunday), whenthe employee has a shift...why isnt my macro reading the data? I pasted the data on a separate tab within the same worksheet. Pls help!

  17. AGG says:

    Hello i am newer to this course so can any one tell me how to start with VBA concept.

  18. ryan says:

    What if you only wanted to apply that VB code to only a couple of columns with the names "Items" and "No."?

  19. Budhaditya says:


    Thanks for sharing this, it was really helpful.

  20. KP says:


    I have run a code but my excel refuses to save when exiting the workbook

  21. David says:

    Is cut and paste between worksheets disabled in macro-enabled worksheets? I thought this would be an easy answer for the internet, but can't find it.

  22. Nausher khan says:

    I can't understand properly.

  23. Drew says:

    Excellent article, I don't think it could have been made any more simple. Thanks

  24. Paul Case says:

    I am trying to input VBA code to determine the indentation in an excel 2010 row.

    the followin was taken from a different forum but When I insert the the code I get and run error message compile error ambuguous name detected: indenture

    this is what I pasted into the window
    Sub indenture()
    Function indenture(r As Range) As Integer
    indenture = r.IndentLevel
    End Function

  25. Akhilesh says:


    I want to lock some of cells ( in all worksheet within a workbook including adding new worksheet, and also do not want to move excel cursor on that cells.
    Where should I type code i.e in module or at workbook.

    Lock cell (A1:C2) and (D2:F4) and (B1:B12) in worksheet as well as adding new worksheet withing a workbook.

  26. Diogo says:

    Alexander, great post.
    I have a doubt about sending a "macroed" excel worksheet to execute in another computer.
    The end user will need to have any special permission to execute macros? (no ActiveX included)
    Because i am planning to distribute an excel file (made in 2010 or 2013), with macros/forms, but i am afraid that it will not be compatible with other excel versions or missing configuration/installed apps in users computers (and i don't have control over those as the file will be to open public).

    Do you know where i can get more information about this?
    Thanks in advance!

  27. sandeep says:

    I want to appended 50 excel files on daily basis. please tell me how to do that on micro level

  28. lina says:

    what if i already have an VB code and i just want to run this code using excel !
    do you have any idea about how to do this ?

  29. Sourabh says:

    What is the desired output of the above Macro file?
    Please let us know since we are new to this.

  30. Chetan Sharma says:

    Hello, This is Chetan
    I have created one custom toolbar as addins that has so many buttons with assigned macros and my query is When I am giving to the client he is not able to use that toolbar???? Here I am able to export the customization that i did but unable to export the VBA code that I have written, after some R&D I came to the point there is one Personal.xlsb file that I need to copy to the client machine on specific XLSTART folder but it's not working because the Psersonal.xlsb is specific to me (specified user who has created )on other system it is asking for my computer location..
    So How can i resolve the issue so that it can work for any computer
    please help me???????????

  31. Chetan+Sharma says:

    How can I create the custom toolbar with VBA code as addins sothat it can work for any computer.
    or there is any installation file that I need to create.
    Please help me??????????

  32. Chetan+Sharma says:

    Thank you for this! You saved me a ton of work of having to do this manually! Very simple instructions with amazing results.

  33. Christophe Pans says:

    If I create a VBA code in Excel version 2010 will it work by someone who has other versions of Excel including 2013 as 2007?
    I want to send a form where the letters automatically change to UPPERCASE when anyone with any kind of excel version types in the cell.

    • Alexander says:

      Hello Christophe,

      Yes, of course. Your code should work in all the versions of Excel you mentioned and even in Excel 2003.
      It won't work in earlier versions only if you are calling new functions of Excel 2010 – 2013 there, but it doesn't look like your case.

  34. Anonymous says:

    can i ask one code in excel macro how can we "enter" using a macro code

  35. Tamsyn says:


    I'm trying to make it so that only one person can access the workbook at once and if anyone else tries do use it they will get a message saying that it's in use by another user.

    I have found the code below on another forum but it doesn't seem to be working - The Macro name won't appear when I try to run it. I think it's to do with the beginning section of code? Your help would be much appreciated!

    Many thanks, Tamsyn

    Private Sub Workbook_Open()
    With Me
    If .ReadOnly Then
    Call MsgBox(Prompt:="The workbook is already open by another user!", _
    Buttons:=vbExclamation + vbOKOnly, _
    Call .Close(SaveChanges:=False)
    End If
    End With
    End Sub

  36. Biyiolanibi says:

    I will like to code my page in excell pla how do I do it.

  37. jeyaganthan.P says:

    hi, i'm jey i want some help i want the exell sheets chenge in between some time limit how to develop it plese send me the code or tips

  38. logesh says:

    Less tension more work - more work less tension

    How.. ?

  39. Rob Garven says:

    Good afternoon

    I have a spreadsheet with about 49,000 lines in it, I need to insert 9 lines between each line of text and am having some issues with the Macro to use. There is only 1 column of text and I just need to insert 9 blank lines between each line of text.

    Is someone able to point me in the right location to get the code to create the macro to do this please?

    Thank you in advance
    Rob Garven

  40. anand says:

    please explain me how to enable or disable .bas in excel

  41. rajdeep says:

    i am working on excel workbook having 1000 worksheets.i want to extract data from all 1000 sheets in rangs(A6, A13:A15, A30:A34, A36:A40). Data present in workbook, are in the above said position in all of the worksheets. so someone provide me a macro for doing this thing.
    thank you for help

  42. meo says:

    Can please give information regarding
    what are the changes that we have to take into account while working excel VBA 2014??
    all my codes are written in VBA 2010 but code are not working in 2014 VBA ?? so please suggest me regarding this

  43. Ankit Garodia says:


    I have VBA code in Sheet3 column A of my excel file. I want to assign a button in sheet1 A1 to copy the vba code from sheet3 colum A and run the script.
    I am not able to put the code to open VBA through macro.
    Please help.

  44. pawan panwar says:

    creat your own funcation -
    Access include many built -in ,or instrinsic ,funcation an intrust payment. you use these funcation to perform calculation without having to creat complicated expressions .using VBA, you can also creat your own funcation to either perfom calculation that excced the capability of an expressions or replace complex expressions you have written in your application.

  45. Ashsih says:

    can u tell which book will be best to learn macro

  46. Rita says:

    Hi, everytime I save as on excel I get strange symbols characters after the file name this is for excel 2013.

  47. Shailesh says:

    Can you tell which book is Best to learn macro in easy way to implement macros in excel**********

  48. Burhan says:

    I have visual program of timestamp whenever i enter sonething time will it complusary to create a macro nd assign prog in it..? Der is no direct method to save dat prog in excel...?

  49. Kirill says:

    Hello Alexander.

    Could you help me with the VBA code to complete the following task:

    I have an excel table. Assuming the formula goes in column D starting the cell D1,

    For i=1 To Countif(A:A,"*")
    Do Until True
    If Left(C1,B(0+i))=A(0+i) Then A(0+i)

    Here B(0+i) should start from B1,then B2, etc. until C1=A1 or A2 or etc.

    For D2 the VBA should do,

    For i=1 To Countif(A:A,"*")
    Do Until True
    If Left(C2,B(0+i))=A(0+i) Then A(0+i)


  50. Anthony says:


    i copied your coding into my excel and saved it correctly, but when i open the file again it gives me an error. when i press alt F8 there are not macros on the list for me to chose from. when i open a new sheet and redo everything then it works but as soon as i save that file and open it i get the same result.

  51. Raje says:

    hello, could anyone help me learn excel macro. i work on automation. im on my training period. and as of now my task is to create the popup calendar, meaning, i need to find people who hav joined on that particular date. i should get the popup calendar, when i click on a particular date, i must get the list of people who hav joined into the organization on that day.


  52. William says:

    Hi im not able to run 2 different modules at the same time using the spellnumber formula i want to be using it for 2 different currencies
    kindly advise

  53. Raj says:


  54. Raj says:

    i m new to this excel and vba but i know vb how to work on this

  55. Michael says:

    Hello All .Very useful article. Would you be able to to help me for the following : i have a text in Excel worksheet that i want to copy and paste into Excel VB Standard Module . Currently I can do it using "Cntl C" to copy and then Cntl V " to paste into Excel VB Module . Can you please suggest some other method of how it can be done without pushing the above buttons.

  56. Mick Alford says:

    Ripper, thanks for this

  57. Danish Bagwan says:

    I m give information for vba programing

  58. Rajkumar says:

    Hello Alexander.

    Could you please let me know why the below code is not running when I click on Run button, there is no response nor error message populated.

    Sub LoopThroughDirectory()

    Dim MyFile As String
    Dim erow
    MyFile = Dir("C:\Users\r628956\Desktop\Salesforce\Rating\Automation\Master")

    Do While Len(MyFile) > 0
    If MyFile = "zmaster.xlsm" Then
    Exit Sub
    End If

    Workbooks.Open (MyFile)

    erow = Sheet1.Cells(Rows.Count, 1).End(x1Up).Offset(1, 0).Row
    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range

    MyFile = Dir

    End Sub

    Thank you - Rajkumar

  59. tevin says:


    How do i change excel sheet1, sheet2,.... at the bottom of the screen, to appear as a navigation tab on top of the screen?

  60. Ashish says:

    now, i want to make Dashboard to Summarise the Sales data, Return, & Stock , Date wise transaction & Unique Column is SKU Code, kindly help me how to process it on every 7 Days, if you have any templet as our Requirement , then pls provide.


  61. dena says:

    I would like to create a macro where you go through the steps to insert a picture into a comment, but i would like to have the macro stop at the insert picture screen so it is simple for whoever is using the document can go directly to the insert a picture popup and finish the request.

  62. Chandini says:

    Hi ,

    Can you please share a copy of a worked file on which macro is created and run to my mail Id as in shared. just to take it as a example and work with


  63. VBAspirer says:

    I created a little ActiveX control (spin up/down)via VBA for my PPT chart. But I can't find anywhere in the videos how to save it in order to use it. Can someone please tell me how or direct me where to go? Thanks.

  64. Surya says:

    I want to put a macro to getting the first line bold on the selected column

    Please help!

  65. Surya says:

    Hi i have used the line break formula, and it is working great.

    Further please help in make macro to break line. As in if there are double spacing in between two words, then that should come in the next line of the cell.


  66. sara says:

    I want to create a data base using excel i want to create it where if i search the item the prices and purchased store will appear

  67. Gopal Menon says:

    Thank you, Alexander.

    You have solved my problem.

  68. Gil says:

    I am opening a "shared" spreadsheet, that sits on our Corporate NAS. I have copied the file off the NAS to my home computer, in order to add some VBA code - for displaying the sheet and refreshing at set intervals. However, when I open the Developer tab and attempt to right click on the sheet, all my options are greyed out? Is this because the sheet has been placed in "shared mode" from within Excel (not sure how to disable that and add the code, then re-enable shared mode). I will need to put it back on the NAS when the code has been added. NB: The VBA code was produced by a freelancer at to refresh each of the four tabs on the sheet, every 15 seconds.. Thanks! (I have a screen capture I could send you).

  69. PAWAN kUMAR says:

    Plz Send All details With Screen Shot.that how to create VBA in Excell Sheet

  70. khush says:

    Hi , I just started with VBA using it for the first time , I wrote code under module but When I am clicking on "Run".
    It is not giving me any result.

    Suppose I use a command :
    Sub hello()
    MsgBox ("Helloworld")
    End Sub

    When I am running it , it is not getting published in Excel workbook

  71. Prasad says:


    I am trying to import data from certain columns from an excel sheet "MyData.xlsx" into "PriceInc.xlsx"

    There is a button on the "PriceInc.xlsx" file that, when clicked should bring in the required data.

  72. Manali says:

    Delete entire row from A2 downwards with the word "0o,rb,t"in column A

  73. Venkat says:

    Thanks for the Aritical.

  74. mbah peter says:

    how do i run a vba code using a macro such that each time i click on the macro, it runs my vba code

  75. mbah peter says:

    thank you sir for treating my worries

  76. Mihalloween says:

    I entered a VBA for excel 2013. I wanted to make a drop down list w/ multi items to select. It works perfectly for me, but when I send it to my associate it does not work...only single selection is possible. Is that because they do not have a, "developer" ribbon? I cannot have everyone do is there a workaround? Thanks for your valuable time!

  77. Amaible says:

    Can anyone tell me that how to run any of macro program in excel?

  78. Dake says:

    Worked great! I didn't bother with any of the added code. Thanks!

  79. a man says:

    it is way too complicated i just want a print screen macro

  80. Excel novice says:

    Where/how do I see the results, after I run the code above?

  81. Quinn Vigie says:

    I need to Increment 50 by 0.64 everyday at 8:00 AM and I would like to automate it. I've already have a Now function that updates every second, I also need a way to start it when Excel is opened.

  82. Frances says:

    I've followed all the steps, but I'm having a problem with the code doing what I need. Instead of adding the dollar amounts in the cells that have a specific colored background, I'm getting how many cells have that colored background. Example: 5 green cells with $20 in each of them, the code gives me $5 when it should be $100.

  83. Vimal Tyagi says:

    Hi Alexander,

    Please help me out when i use VBA coding for Consolidated Data show this error.

    Microsoft Visual Basic for Applications
    Compile error:

    Sub or Function not defined
    OK Help

  84. Naveen says:

    Hi sir
    I want VBA code for to display the excel data in text box. For example 3 text boxes in VBA form in excel a1,b1,c1 have data. If a1 and b1 data typed in text box 1 and 2 c1 data will display in textbox3.

  85. Tj says:

    Is there a way to have this constant and not having to run the Macro for it to be applied?

  86. Muhammed says:

    A notification bar appears which reads:
    Be careful! Parts of your document may include personal information that cannot be removed by the Document Inspector

  87. Pete says:


    I am trying to create a button in excel that when clicked it, will add 1 point to a score on different sheet (sheet 2). I can't seem to find out if this is possible, and if it is, how to do it.

    Ideally I want to have multiple buttons so I can create scoring charts (team 1's score in B1, team 2's score in B2, etc) but you won't be able to see it until you go on to sheet 2.

    Any help would be gratefully received!

  88. UDay says:


    How to run macro in MS Task scheduler, please help me.

  89. Girish says:

    Can this code be applied to all worksheets? if yes help me make it permanent in excel. I tried to save as a add-in but its not working all workbooks.

  90. Trev says:

    I want to save a running total from a cell in Excel and wondered can this be done? I have a formula to put the total in a cell on a certain date but when the date has passed it clears the cell again and I want the running total on that date to be captured. My formaula in excel to capture data on a certian date is:- =IF(D2=(DATE(2017,6,11)),D3,0)

    Thanks for any info, Cheers Trev

  91. firaas says:

    I wanted to have the Grouping function on a protected excel. I got a solution on the web, for a vba code to be used.
    link -

    But the issue is that I want it all the time on the excel. How can I save it so that each time I open the excel, the function is working for grouping and ungrouping in the excel template.


  92. Rebecca R says:

    I went through the steps above to add VBA code to my spreadsheet, however, when opening the macro, there is nothing listed for selection. Why is that? (In other words, I can see the information through ALT + F11, but when selecting ALT + F8, the macro is not there).

  93. Ravi K says:


    Please help me. I want to color cell background by comparing with cell value and one more cell value. Example: Col A (1:10) has values 0 & 1. Col B:E (B1:E10) has values of 1-100. Color B1:E10 if the value of cell >50 & A1 equal to 0. Total four colors and four conditions.
    1) A1:A10 = 0 then B1:E10 =50
    3) A1:A10 = 1 then B1:E10 =50

    I am able to create only for if B1:E10 >/<50.


  94. dharmaraja says:

    how to use a module in a userform more than textboxes in same module
    please given the code and how to create a time symbol provide a number format example (1230 =12:30) in this code give to me
    thanks you

  95. Yash says:

    Thank you so much! I've never added a macro and the steps were super easy to follow. Easy fix.

  96. Shamla says:

    Hi. I'm using a macro to combine multiple sheets in one excel workbook. Macro works but I keep getting a screen that asks me if I want to save or dont save I want to add this step into the macro, can someone please help?
    Thank you in advance.

    Sub GetSheets()
    Path = "\\>>>>>>>>>Extract for CD 20171027\"
    Filename = Dir(Path & "*.xls")
    Do While Filename ""
    Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
    For Each Sheet In ActiveWorkbook.Sheets
    Sheet.Copy After:=ThisWorkbook.Sheets(1)
    Next Sheet
    Filename = Dir()
    End Sub

  97. Shane N says:

    This is excellent! I work at an I-Bank this is gold! Thank you Sir.

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