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

251 comments

  1. morning

    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.

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

    Thanks

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

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

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

  6. can u tell which book will be best to learn macro

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

  8. Hi,

    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.

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

  10. hi.
    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

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

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

  13. Less tension more work - more work less tension

    How.. ?

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

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

  16. Hi,

    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, _
    Title:="Closing...")
    Call .Close(SaveChanges:=False)
    End If
    End With
    End Sub

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

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

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

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

  20. 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??????????

  21. 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???????????

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

  23. 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 ?

    • Hello Lina,

      This is exactly what is told in the article. Could you please specify on what step you have difficulties?

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

  25. 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!

  26. Hi,

    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.

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

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

    • Hello, Paul,

      The first line is redundant, you just need:

      Function indenture(r As Range) As Integer
      indenture = r.IndentLevel
      End Function

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

  29. I can't understand properly.

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

  31. Hi,

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

  32. Hi,

    Thanks for sharing this, it was really helpful.

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

    • Hello Ryan
      As far as I understand, you have a VB code that you want to modify in the way to apply it only to certain columns.
      If it is your case, I am sorry we can't help you with this. Please look for the solution on these forums: http://www.mrexcel.com or http://www.excelforum.com

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

  35. 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!

  36. Great post thanks for help me out!

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

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

  38. Thank you, thank you, thank you.

  39. I am sanjeev .I am new in excel....so 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............

    worksheets("sheet2").activate

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

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

    • Hello parvin,
      I am not sure I fully understand your requirement. Can you please explain in more detail?

    • Parvin - I just wrote a macro that pull data from the filled fields in a PDF

  41. Hi,

    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.

    Thanks,
    Rumana

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

  43. 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!

    • Sorry, I cannot suggest a solution off the top of my head. This kind of task requires some research and coding. You can try searching for a solution on Excel forums like Mrexcel.com or excelforum.com

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

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

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

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

    • Your Sub/Function can not be Private.... If they are, they won't be visible when you press Alt-F8.

    • I'm not sure if people are still looking at this forum... but I have the same exact problem as Angel.

  46. hello,
    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?

    • * correction - it is blank - no black

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

  48. 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?

    Thanks,

    Jim

    • Hello Jim,
      There may be various reasons. But I do not think this is a compatibility issue because Microsoft really cares to make Office applications backward compatible.

      • i made a excel vba. it works but when i close it and open it again the vba doesn't work but the codes still there what is the problem... can you help me? thank you!!!

  49. Hello There,

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

    Regards
    Syed

      • 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?

  50. Hi,

    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.

    Regards,
    Hemanth C
    9449330057

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