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

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

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

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

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

    Those convert a no in to write text

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

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

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

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

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

  11. Works perfectly! Thanks!

  12. I was wondering how I can modify the code to have all the excel files into 1 sheet instead of each individual sheets? Thank you

  13. Hello, i would like to change the address from where i am sending all the emails using the VBA macro excel. How do i change that? i dont know i am clear o not. Every time i send the emails from the VBA macro i would like to that "sender" appears a different email address than from where i am really am sending from.

  14. I am new so hope you can help.
    I would like to write code for registration of players and teams. How do I start please?
    Thanks
    John

  15. I want to develop a VBA code; let us suppose we have values like 1 2 3 4 5 in col A1 A2 A3 A4 A5 and other values like 6 7 8 9 10 in col B1 B2 B3 B4 B4 B5 and I want to write 1/6 2/7 3/8 4/9 5/10 in columns C1 C2 C3 C4 C5.

  16. Is it possible to call excell or word, without needing to specify which version (ie word 14, word 15 etc).

  17. in vba modules are saved by which extension

  18. Hi
    I am wanting to make a Commond Button that will insert a new row below the active cell and in the new row have formulas automatically populated.
    ie say active cell is D8 the press the Button and a new row is added to Row 9 which now includes the formula =sum(D7+B6) in the new cell C9 and the formula =sum(a2-a5) in cell e9.

    Thank

  19. Hi
    please I need assistance in converting the word into numbers

    example: let say the word (Rawad) and we have R = 10 , A = 1 , W = 700 and D = 3

    so the total of word Rawad must be 10 + 1 + 700 + 1 + 3 = 715

    thanks in advance

  20. Sir please forward Ur good comments that how I easily access what kind of book in Pakistan for learning VBA codes.

  21. How I made search button in excel VBA

  22. Hi - I am trying to create a Button in my sheet for a randomizer formula I set up. Basically, I have a list A:A of SKU names and B:B Random(1,5000)
    I want the button to auto-generate a 10 item SKU list that can be used for Inventory Cycle Counting. I set up the button but can not get any further with the visual basic script (newbie)

  23. dear sir\madam
    please tell me how to learn vba macros coding in excel sheets
    please help me

  24. I am failing to locate and make the Vb code

  25. Hi I cannot figure out how to have a row of possible 100 numbers that when I enter a number in cell A1 all the numbers move up one cell and the new number appears in B1 any help would be appreciated

  26. Hi,
    If i run the macro its successfully run ,while the next time i get an error . Kindly help what are the comment i need to use

  27. I performed the task but my spreadsheets did not merge what did I do wrong? All of the examples I followed but after the Alt F8 I was lost because it did not show what to do next or what I should be looking for.
    thanks

  28. Is import function runs in excel 2010? previously i created a code using import function to import .bas file into many excels sheets by running this code. now this in not working for excel 2010. can anybody please help me out here?

    • Code:
      ActiveWorkBook.VBProject.VBComponents.Import ("C:\.....code.bas")

  29. I only need to remove carrigae returns in 1 column in my case Column H.

    How can I define the range to be H, and not the whole sheet?

    Thanks

  30. can you please tell how to copy paste from row1(sheet1) to any cell in sheet2.. and create a button for going to next row in sheet1

  31. VBA Macro for Change Case works well
    thank you very much

  32. Dear hoe to i set vba project in colum as(rohit kumar parasshar)in single colum i read in a video (by right click view code entir.excel.com

    (Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    ...................what i write heare
    End Sub)

  33. There are many mistakes in this post

  34. Im afraid horrible text and doesnt work

  35. This does not work

  36. I want to thank you for this code and tutorial. I don't write VB code and just need a quick solution to a problem and this resolved it. Thank you so much for your time and effort.

  37. Hi I am trying to create a template workbook for some data analysis. I have worked it up but now need to delete the data and save it as a template.

    I was just wondering if you have a workbook that has a VBA code attached if it is save as a macro enabled workbook do you have to add the code again when you reopen the workbook?

    Many thanks,

    Karen

    • Karen:
      When you put the VBA in the module and saved it, the code would be in Excel. It would be available to be called from inside that workbook. Click Alt-F8 and you can see what code is available in that workbook. You should see the names of the modules you built and saved.

  38. Dear Sir / Madam.
    I have made a user form with 7 entries. I would like to have an Even number to become a Red font through my user form. So if the number is 346 then this number and all the other 7 boxes become a red font. Any help would be greatly appreciated. I just don't know what to write.
    Thanks and Kind regards
    Rob

  39. Thank you. Works perfectly!!

  40. Hi there,
    I tried your code but it doesn't do anything. No messages, nothing. What am I doing wrong?

    • the same here!!

      • Same for me

  41. I just want to say thank you for this fantastic, simple solution and for your awesome products in general.

  42. Hello,

    I want a code which is used to cut the rows having the red color and paste in another sheet and when color changes to white should transfer to same sheet (online spread sheets)

  43. IT IS VERY NICE THANK YOU

  44. Hellow Team,

    we need your help for VBA Coding in excel i don't know VBA coding how to start
    learning VBA Coding.

    • Please help me to reference link to enhance skills I vBa

  45. Hello,

    Anyone who can assist me to provide a vba code on how to generate a responses that will be consolidated to another worsheet. Example, Response with "Will be included in the remediation" and "Partial Remediation" will be generated to the consolidated worksheet. Thanks

  46. Hi All,

    I would appreciate if someone could help me with some VBA coding I need to do. I am creating a userform for an excel document. It is quite simple but I really dont know how VBA coding works. I have 6 categories in my spreadsheet that have got to filled up in the form with numbers from 1/10 and then there is a comments box to for extra comments and a name box for the user name. finally it has 2 command boxes: Add company and close form.
    I have done the form now and given the usual names to the boxes such as:
    txtname
    cboquality
    cboprice
    cbostock
    cmdAdd
    cmdClose
    Can someone help me out with the code so that once the form is filled and the command box for add clicked all the information goes to the spreadsheet?

    It would be greatly appreciated

  47. Thank You! Big help!

  48. Hi!
    If i can't save file after i add this VBA code. It says that there is an error and Excel may able to save file by removing or repairing some features. Options are to click continue or cancel. When clicking continue it want to save file as another one, but in the end it says :file was not saved".

  49. Thank you so much. Big help.

  50. Excellent guideline. Thanks.

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