The Ultimate VBA Tutorial Part One

VBA Tutorial

“The noblest pleasure is the joy of understanding.” – Leonardo da Vinci

 
Welcome to part one of the Ultimate VBA Tutorial.

If you are brand new to VBA, then make sure that you have read the post How To Create a Macro From Scratch in Excel so that your environment is set up correctly to run macros.

In this tutorial you will learn how to create real-world macros. The focus is on learning by doing. This tutorial has coding examples and activities to help you on your way. You will find a quiz at the end of the tutorial. You can use this to test your knowledge and see how much you have learned.

In part one of the tutorial we will concentrate on the basics of creating Excel macros. See the next sections for the learning outcomes and for tips on getting started with VBA.

 

Learning Outcomes

When you finish this tutorial you will be able to:

  1. Create a module
  2. Create a sub
  3. Understand the difference between a module and sub
  4. Run the code in a sub
  5. Write a value to a cell
  6. Copy the value from one cell to another
  7. Copy values from one range of cells to another
  8. Copy values between difference worksheets
  9. Test your output using the Immediate Window
  10. Write code faster using the With Statement
  11. Create and use variables
  12. Copy from a cell to a variable and vice versa

 

Before we get started, let’s look at some simple tips that will help you on your journey.

6 Tips For Learning VBA

  1. Practice, Practice, Practice – Don’t try to learn by reading. Try the examples and activities.
  2. Type the code examples instead of copying and pasting – this will help you understand the code better.
  3. Have a clearly defined target for learning VBA. One you will know when you reach.
  4. Don’t be put off by errors. They help you write proper code.
  5. Start by creating simple macros for your work. Then create more complex ones as you get better.
  6. Don’t be afraid to work through each tutorial more than once.The more times you do it the more deeply embedded the knowledge will become.

 

Basic Terms and What They Mean

Excel Macros: A macro is a group of programming instructions we use to create automated tasks.

VBA: VBA is the programming language we use to create macros. It is short for Visual Basic for Applications.

Line of code: This a VBA instruction. Generally speaking, they perform one task.

Sub: A sub is made up of one or more lines of code. When we “Run” the sub, VBA goes through all the lines of code and carries out the appropriate actions. A macro and a sub are essentially the same thing.

Module: A module is simply a container for our subs. A module contains subs which in turn contain lines of code. There is no limit(within reason) to the number of modules in a workbook or the number of subs in a module.

VBA Editor: This is where we write our code. Pressing Alt + F11 switches between Excel and the Visual Basic Editor. If the Visual Basic editor is not currently open then pressing Alt + F11 will automatically open it.

The screenshot below show the main parts of the Visual Basic Editor
 

The Visual Basic Editor

 

Tip for the Activities

When you are working on the activities it is a good idea to close all other Excel workbooks.

 

Creating a Module

In Excel, we use the VBA language to create macros. VBA stands for Visual Basic for Applications.

When we use the term Excel Macros we are referring to VBA. The term macro is essentially another name for a sub. Any time you see the terms Excel Macros or VBA just remember they are referring to the same thing.

In VBA we create lines of instructions for VBA to process. We place the lines of code in a sub. These subs are stored in modules.

We can place our subs in the module of the worksheet. However, we generally only place code for worksheet events here.

In VBA, we create new modules to hold most of our subs. So for our first activity let’s go ahead and create a new module.

 
 

 Activity 1

 

  1. Open a new blank workbook in Excel.
  2. Open the Visual Basic Editor(Alt + F11).
  3. Go to the Project – VBAProject window on the left(Ctrl + R if it is not visible).
  4. Right-click on the workbook and click Insert and then Module.
  5. Click on Module1 in the Project – VBAProject window.
  6. In the Properties window in the bottom left(F4 if not visible), change the module name from module1 to MyFirstModule.

 

 End of Activity 1

 
 
The module is where you place your code. It is simply a container for code and you don’t use it for anything else.

You can think of a module like a section in a bookshop. It’s sole purpose is to store books and having similar books in a particular section makes the overall shop more organised.

The main window(or code window) is where the code is written. To view the code for any module including the worksheets you can double-click on the item in the Project – VBAProject window.

Let’s do this now so you can become familiar with the code window.

 

 Activity 2

 

  1. Open a new workbook and create a new module like you did in the last activity.
  2. Double-click on the new module in the Project – VBAProject window.
  3. The code window for this module will open. You will see the name in the title bar of Visual Basic.

 
VBA Tutorial 2A

 

 End of Activity 2

 
You can have as many modules as you like in a workbook and as many subs as you like within a module. It’s up to you how you want to name the modules and how you organise your subs within your modules.

 

How to Use Subs

A line of code is the instruction(s) we give to VBA. We group the lines of code into a sub. We place these subs in a module.

We create a sub so that VBA will process the instructions we give it. To do this we get VBA to Run the sub. When we select Run Sub from the menu, VBA will go through the lines of code in the sub and process them one at a time in the order they have been placed.

Let’s go ahead and create a sub. Then afterwards, we will have a look at the lines of code and what they do.

 

 Activity 3

 

    1. Take the module you created in the last activity or create a new one.
    2. Select the module by double-clicking on it in the Project – VBAProject window. Make sure the name is visible in the title bar.
    3. Enter the following line in the code window and press enter.
    4.  

      Sub WriteValue
      

       

    5. VBA will automatically add the second line End Sub. We place our code between these two lines.
    6. Between these two lines enter the line
    7.  

       Sheet1.Range("A1") = 5
      

       
      You have created a sub! Let’s take it for a test drive.
       

    8. Click in the sub to ensure the cursor is placed there. Select Run->Run Sub/Userform from the menu(or press F5).
      Note: If you don’t place the cursor in the sub, VBA will display a list of available subs to run.
    9. Open Excel(Alt + F11). You will see the value 5 in the cell A1.
    10. Add each of the following lines to your sub, run the sub and check the results.

     

    Sheet1.Range("B1") = "Some text"
    Sheet1.Range("C3:E5") = 5.55
    Sheet1.Range("F1") = Now
    

     
    You should see “Some text” in cells B1, 5.55 in the cells C3 to E5 and the current time and date in the cell F1.
     


     

     End of Activity 3

     

    Writing values to cells

    Let’s look at the line of code we used in the previous section

    Sheet1.Range("A1") = 5
    

     
    We can also write this line like this

    Sheet1.Range("A1").Value = 5
    

     
    However in most cases we don’t need to use Value as this is the default property.

    We use lines of code like these to assign(.i.e. copy) values between cells and variables.

    VBA evaluates the right of the equals sign and places the result in the variable/cell/range that is to the left of the equals.

    The line is saying “the left cell\variable\range will now be equal to the result of the item on the right”.

    Tutorial 1 Assignment line parts

     
    Let’s look the part of the code to the left of the equals sign

    Sheet1.Range("A1") = 5
    

    In this code , Sheet1 refers to the code name of the worksheet. We can only use the code name to reference worksheets in the workbook containing the code. We will look at this in the section The code name of the worksheet.

    When we have the reference to a worksheet we can use the Range property of the worksheet to write to a range of one or more cells.

    Using a line like this we can copy a value from one cell to another.

     
    Here are some more examples

    Sub CopyValues()
        
        ' copies the value from C2 to A1
        Sheet1.Range("A1") = Sheet1.Range("C2")
        
        ' copies the value from D6 to A2
        Sheet1.Range("A2") = Sheet1.Range("D6")
        
        ' copies the value from B1 on sheet2 to A3 on sheet1
        Sheet1.Range("A3") = Sheet2.Range("B1")
        
        ' writes result of D1 + D2 to A4
        Sheet1.Range("A4") = Sheet2.Range("D1") + Sheet2.Range("D2")
        
    End Sub
    

     
    Now it’s your turn to try some examples. Copying between cells is a fundamental part of Excel VBA, so understanding this will really help you on your path to VBA mastery.
     

     Activity 4

     

    1. Create a new Excel workbook.
    2. Manually add values to the cells in sheet1 as follows: 20 to C1 and 80 to C2.
    3. Create a new sub called Act4.
    4. Write code to place the value from C1 in cell A1.
    5. Write code to place the result of C2 + 50 in cell A2.
    6. Write code to multiply the values in cells C1 and C2. Place the results in cell A3.
    7. Run the code. Cells should have the values A1 20, A2 130 and A3 1600

     

     

     End of Activity 4

     

    Cells in Different Sheets

    We can easily copy between cells on difference worksheets. It is very similar to how we copy cells on the same worksheet. The only difference is the worksheet names which we use in our code.

    In the next activity we are going to write between cells on different worksheets.

     

     Activity 5

     

    1. Add a new worksheet to the workbook from the last activity. You should now have two worksheets called which are called Sheet1 and Sheet2.
    2. Create a new sub call Act5.
    3. Add code to copy the value from C1 on Sheet1 to cell A1 on Sheet2.
    4. Add code to place the result from C1 + C2 on Sheet1 to cell A2 on Sheet2.
    5. Add code to place the result from C1 * C2 on Sheet1 to cell A3 on Sheet2.
    6. Run the code in the sub(F5). Cells on Sheet2 should have the values as follows:
      A1 20, A2 100 and A3 1600

     


     

     End of Activity 5

     
     

    The Code Name of the Worksheet

    In the activities so far, we have been using the default names of the worksheet such as Sheet1 and Sheet2. It is better practice to give these sheets more meaningful names.

    We do this by changing the code name of the worksheet. Let’s look at the code name and what it is.

    When you look in the Project – VBAProject window for a new workbook you will see Sheet1 both inside and outside of parenthesis.

     
    VBA Code name
     

    • Sheet1 on the left is the code name of the worksheet.
    • Sheet1 on the right(in parenthesis) is the worksheet name. This is the name you see on the tab in Excel.

     
    The code name has the following attributes

    1. We can use it to directly reference the worksheet as we have been doing e.g.
    2.  

      Sheet1.Range("A1")
      

       
      Note: We can only use the code name if the worksheet is in the same workbook as our code.
       

    3. If the worksheet name is changed our code will still work if we are using the code name to refer to the sheet.

     
     
    The worksheet name has the following attributes

    1. To reference the worksheet using the worksheet name we need to use the worksheets collection of the workbook. e.g.
    2.  

      ThisWorkbook.Worksheets("Sheet1").Range("A1")
      

       

    3. If the worksheet name changes then we need to change the name in our code. For example, if we changed the name of our sheet from Sheet1 to Data then we would need to change the above code as follows
    4.  

      ThisWorkbook.Worksheets("Data").Range("A1")
      

     
     
    We can only change the code name in the Properties window.
    We can change the worksheet name from both the worksheet tab in Excel and from the Properties window.
     
    VBA Code name
     
     
    worksheet name on tab
     
     
    In the next activity we will change the code name of the worksheet.
     

     Activity 6

     

    1. Open a new blank workbook and go to the Visual Basic editor.
    2. Click on Sheet1 in the Project – VBAProject Window(Ctrl + R if not visible).
    3. Go to the Properties window(F4 if not visible).
    4. Change the code name of the worksheet to shReport.
    5. Create a new module and call it modAct6.
    6. Add following sub and run it(F5)
    7.  

      Sub UseCodename()
          shReport.Range("A1") = 66
      End Sub
      

       

    8. Then add following sub and run it(F5)
    9.  

      Sub UseWorksheetname()
          ThisWorkbook.Worksheets("Sheet1").Range("B2") = 55
      End Sub
      

       

    10. Cell A1 should now have the value 66 and cell B2 should have the value 55.
    11. Change the name of the worksheet in Excel to Report i.e. right-click on the worksheet tab and rename.
    12. Delete the contents of the cells and run the UseCodename code again. The code should still run correctly.
    13. Run the UseWorksheetname sub again. You will get the error “Subscript out of Range”. This crytically sounding error simply means that there is no worksheet called Sheet1 in the worksheets collection.
    14. Change the code as follows and run it again. The code will now run correctly.
    15.  

      Sub UseWorksheetname()
          ThisWorkbook.Worksheets("Report").Range("B2") = 55
      End Sub
      

       

     


     

     End of Activity 6

     

    The With keyword

    You may have noticed that we need to use the worksheet name repeatedly – each time we refer to a range in our code.

    Imagine there was a simpler way of writing the code. Where we could just mention the worksheet name once and VBA would apply to any range we used after that. The good news is we can do exactly that using the With statement.

    In VBA we can take any item before a full stop and use the With statement on it. Let’s rewrite some code using the With statement.

     
    The following code is pretty similar to what we have been using so far

    Sheet1.Range("A1") = Sheet1.Range("C1")
    Sheet1.Range("A2") = Sheet1.Range("C2") + 50
    Sheet1.Range("A3") = Sheet1.Range("C1") * Sheet1.Range("C2")
    

     

    Let’s update this code using the With statement

    With Sheet1
        .Range("A1") = .Range("C1")
        .Range("A2") = .Range("C2") + 50
        .Range("A3") = .Range("C1") * .Range("C2")
    End With
    

     

    We use With and the worksheet to start the section. Anywhere VBA finds a full stop it knows to use the worksheet before it.

    We can use the With statement with other types of objects in VBA including workbooks, ranges, charts and so on.

    We signify the end of the With section by using the line End With.

     
    Indenting(Tabbing) the Code
    You will notice that the lines of code between the start and end With statments are tabbed once to right. We call this indenting the code.

    We always indent the code between VBA sections that have a starting line and end line. Examples of these are as subs, the With statement, the If statement and the For loop.

    You can tab the lines of code to the right by selecting the appropriate lines of code and pressing the Tab key. Pressing Shift and Tab will tab to the left.

    Tabbing(or indenting) is useful because it makes our code more readable.

     

     Activity 7

     

    1. Rewrite the following code using the With statement. Don’t forget to indent the code.

     

    Sub UseWith()
    
    Sheet1.Range("A1") = Sheet1.Range("B3") * 6
    Sheet1.Cells(2, 1) = Sheet1.Range("C2") + 50
    Sheet1.Range("A3") = Sheet2.Range("C3")
    
    
    End Sub
    

     

     

     End of Activity 7

     

    Copying values between multiple cells

    You can copy the values from one range of cells to another range of cells as follows

    Sheet2.Range("A1:D4") = Sheet2.Range("G2:I5").Value
    

     
    It is very important to notice than we use the Value property of the source range. If we leave this out it will write blank values to our destination range.

    ' the source cells will end up blank because Value is missing
    Sheet2.Range("A1:D4") = Sheet2.Range("G2:I5")
    

     

    The code above is a very efficient way to copy values between cells. When people are new to VBA they often think they need to use some form of select, copy and paste to copy cell values. However these are slow, cumbersome and unnecessary.

    It is important that both the destination and source ranges are the same size.

    • If the destination range is smaller then only cell in the range will be filled. This is different to copy/pasting where we only need to specify the first destination cell and Excel will fill in the rest.
    • If the destination range is larger the extra cells will be filled with #N/A.

     

     Activity 8

     

    1. Create a new blank workbook in Excel.
    2. Add a new worksheet to this workbook so there are two sheets – Sheet1 and Sheet2.
    3. Add the following data to the range C2:E4 on Sheet1
    4.  
      VBA Tutorial Act 7
       

    5. Write code to copy the data from Sheet1 to the range B3:D5 on Sheet2.
    6. Run the code(F5).
    7. Clear the results and then change the assignment range to be smaller than the source range. Run again and check the results.
    8. Clear the results and then change the assignment range to be larger than the source range. Run again and check the results.

     

     

     End of Activity 8

     

    Transposing a Range of Cells

    If you need to transpose the date(convert from row to column and vice versa) you can use the WorksheetFunction Transpose.

    Place the values 1 to 4 in the cells A1 to A4. The following code will write the values to E1 to H1

    Sheet1.Range("E1:H1") = WorksheetFunction.Transpose(Sheet1.Range("A1:A4").Value)
    

     

    The following code will read from E1:H1 to L1:L4

    Sheet1.Range("L1:L4") = WorksheetFunction.Transpose(Sheet1.Range("E1:H1").Value)
    

     

    You will notice that these lines are long. We can split one line over multiple lines by using the underscore(_) e.g.

    Sheet1.Range("E1:H1") = _ 
        WorksheetFunction.Transpose(Sheet1.Range("A1:A4").Value)
    
    Sheet1.Range("L1:L4") = _
        WorksheetFunction.Transpose(Sheet1.Range("E1:H1").Value)
    

     
    We can also use a double With statement to make this line neater

    With Sheet1
        
        With WorksheetFunction
            .Range("E1:H1") = .Transpose(.Range("A1:A4").Value)
            .Range("L1:L4") = .Transpose(.Range("E1:H1").Value)
        End With
        
    End With
    

     

    How to Use Variables

    Variables are an essential part of every programming language.

    So what are they and why do you need them?

    Variables are like cells in memory. We use them to store temporary values while our code is running.

    We do three things with variables

    1. Declare(i.e. Create) the variable.
    2. Store a value in the variable.
    3. Read the value stored in the variable.

     
    The variables types we use are the same as the data types we use in Excel.

     
    The table below shows the common variables. There are other types but you will rarely use them. In fact you will probably use Long and String for 90% of your variables.

    TypeDetails
    BooleanCan be true or false only
    Currencysame as decimal but with 4 decimal places only
    DateUse for date/time
    DoubleUse for decimals
    Long Use for integers
    StringUse for text
    VariantVBA will decide the type at runtime

     

    Declaring Variables

    Before we use variables we should create them. If we don’t then we can run into various problems.

    By default, VBA doesn’t make you declare variables. However, we should turn this behaviour on as it will save us a lot of pain in the long run.

     
    To turn on “Require Variable Declaration” we add the following line to the top of our module

    Option Explicit
    

     
     
    To get VBA to automatically add this line, select Tools->Options from the menu and check Require Variable Declaration. Anytime you create a new module, VBA will add this line to the top.

    VBA Option Explicit

     
     
    Declaring a variable is simple. We use the format as follows

    Dim variable_name As Type
    

     
     
    We can use anything we like as the variable name. The type is one of the types from the table above. Here are some examples of declarations

    Dim Total As Long
    Dim Point As Double
    Dim Price As Currency
    Dim StartDate As Date
    Dim CustomerName As String
    Dim IsExpired As Boolean
    Dim Item As Variant
    

     
     
    To place a value in a variable we use the same type of statement we previously used to place a value in a cell. That is, the statement with the equals sign.

    Dim Total As Long
    Total = 1
        
    Dim Price As Currency
    Price = 29.99
    
    Dim StartDate As Date
    StartDate = #1/21/2018#
    
    Dim CustomerName As String
    CustomerName = "John Smith"
    

     

     Activity 9

     

    1. Create a new sub and call it UsingVariables.
    2. Declare a variable for storing a count and set the value to 5.
    3. Declare a variable for storing the ticket price and set the value to 99.99.
    4. Declare a variable for storing a country and set the value to “Spain”.
    5. Declare a variable for storing the end date and set the value to 21st March 2020.
    6. Declare a variable for storing if something is completed. Set the value to False.

     

     

     End of Activity 9

     

    The Immediate Window

    VBA has a real nifty tool that allows us to check our output. This tool is the Immediate Window. By using the Debug.Print we can write values, text and results of calculations to the Immediate Window.

    To view this window you can select View->Immediate Window from the menu or press Ctrl + G.

     
    The values will be written even if the Immediate Window is not visible.

     

     

    We can use the Immediate Window to write out our variables so as to check the values they contain.

     
    If we update the code from the last activity we can write out the values of each variable. Run the code below and check the result in the Immediate Window(Ctrl + G if not visible).

    Sub WritingToImmediate()
        
        Dim count As Long
        count = 5
        Debug.Print count
        
        Dim ticketprice As Currency
        ticketprice = 99.99
        Debug.Print ticketprice
        
        Dim country As String
        country = "Spain"
        Debug.Print country
        
        Dim enddate As Date
        enddate = #3/21/2020#
        Debug.Print enddate
        
        Dim iscompleted As Boolean
        iscompleted = False
        Debug.Print iscompleted
            
    End Sub
    

     
    The Immediate is very useful for testing output before we write it to worksheets. We will be using it a lot in these tutorials.

     

    Writing between variables and cells

    We can write and read values between cells and cells, cells and variables,and variables and variables using the assignment line we have seen already.

    Here are some examples

    Sub VariablesCells()
    
        Dim price1 As Currency, price2 As Currency
        
        ' place value from A1 to price1
        price1 = Sheet1.Range("A1")
        
        ' place value from price1 to price2
        price2 = price1
        
        ' place value from price2 to cell b2
        Sheet1.Range("B2") = price2
        
        ' Print values to Immediate window
        Debug.Print "Prince 1 is " & price1
        Debug.Print "Prince 2 is " & price2
    
    End Sub
    

     

     

     Activity 10

     

    1. Create a blank workbook and a worksheet so it has two worksheets: Sheet1 and Sheet2.
    2. Place the text “New York” in cell A1 on Sheet1. Place the number 49 in cell C1 on Sheet2.
    3. Create a sub that reads the values into variables from these cells.
    4. Add code to write the values to the Immediate window.

     

     

     End of Activity 10

     

    Type Mismatch Errors

    You may be wondering what happens if you use an incorrect type. For example, what happens if you read the number 99.55 to a Long(integer) variable type.

    What happens is that VBA does it best to convert the variable. So if we assign the number 99.55 to a Long type, VBA will convert it to an integer.

    In the code below it will round the number to 100.

    Dim i As Long
    i = 99.55
    

     
     
    VBA will pretty much convert between any number types e.g.

    Sub Conversion()
    
        Dim result As Long
        
        result = 26.77
        result = "25"
        result = 24.55555
        result = "24.55"  
        Dim c As Currency
        c = 23
        c = "23.334"
        result = 24.55
        c = result
    
    End Sub
    

     
     
    However, even VBA has it’s limit. The following code will result in Type Mismatch errors as VBA cannot convert the text to a number

    Sub Conversion()
    
        Dim result As Long
        
        result = "26.77A"
        
        Dim c As Currency
        c = "a34"
    
    End Sub
    

     

    Tip: The Type Mismatch error is often caused by a user accidently placing text a cell that should have numeric data.

     

     Activity 11

     

    1. Declare a Double variable type called amount.
    2. Assign a value the causes a Type Mismatch error.
    3. Run the code and ensure the error occurs.

     

     

     End of Activity 11

     

    End of Tutorial Assignment

    We’ve covered a lot of stuff in this tutorial. So let’s put it all together in the following assignment

     

     Tutorial One Assignment

    I have created a simple workbook for this assignment. You can download it using the link below

    Tutorial One Assignment Workbook

     
    Open the assignment workbook. You will place your code here

    1. Create a module and call it Assignment1.
    2. Create a sub called Top5Report to write the data in all the columns from the top 5 countries to the Top 5 section in the Report worksheet. This is the range starting at B3 on the Report worksheet. Use the code name to refers to the worksheets.
    3. Create a sub call AreaReport to write all the areas size to the All the Areas section in the Report worksheet. This is the range H3:H30. Use the worksheet name to refer to the worksheets.
    4. Create a sub called ImmediateReport as follows, read the area and population from Russia to two variables. Print the population per square kilometre(pop/area) to the Immediate Window.
    5. Create a new worksheet and call it areas. Set the code name to be shAreas. Create a sub called RowsToCols that reads all the areas in D2:D11 from Countries worksheet and writes them to the range A1:J1 in the new worksheet Areas.

     

     

    End of Tutorial Assignment

     

    The following quiz is based on what we covered this tutorial.
     

    Tutorial One Quiz

     

    1. What are the two main differences between the code name and the worksheet name?
    2.  

       

    3. What is the last line of a Sub?
    4.  

       

    5. What statement shortens our code by allowing us to write the object once but refer to it multiple times?
    6.  

       

    7. What does the following code do?
    8.  

      Sheet1.Range("D1") = result
      

       

       

    9. What does the following code do?
    10.  

      Sheet1.Range("A1:C3") = Sheet2.Range("F1:H3")
      

       

       

    11. What is the output from the following code?
    12.  

      Dim amount As Long
      amount = 7
      
      Debug.Print (5 + 6)  * amount  
      

       

       

    13. What is the output from the following code?
    14.  

      Dim amt1 As Long, amt2 As Long
      
      amt1 = "7.99"
      Debug.Print amt1
      
      amt2 = "14a"
      Debug.Print amt2
      

       

       

    15. If we have 1,2 and 3 in the cells A1,A2 and A3 respectively, what is the result of the following code?
    16.  

      Sheet1.Range("B1:B4") = Sheet1.Range("A1:A3").Value
      

       

       

    17. What does the shortcut key Alt + F11 do?
    18.  

       

       

    19. In the following code we declare a variable but do not assign it a value. what is the output of the Debug.Print statement?
    20.  

      Dim amt As Long
      
      Debug.Print amt
      

       

       

     
     

    Conclusion of Tutorial One

    Congratulations on finishing tutorial one. If you have completed the activities and the quiz then you will have learned some important concepts that will stand to you as you work with VBA.

    In the Tutorial 2, we are going to deal with ranges where the column or row may differ each time the application runs. In this tutorial, we will cover

    • How to get the last row or column with data.
    • The amazingly efficient CurrentRegion property.
    • How to use flexbile rows and columns.
    • When to use Range and when to use Cells.
    • and much more…

    .
     
    See you in Tutorial 2

53 comments

  1. Hi Paul,
    Congratulations for the clarity and objectivity of this tutorial.
    Once again, a great job. 🙂

  2. Great tutorial, Paul!

    When I tried this line of code: Sheet1.Range(“A1”) = 5 , VBA throws “Variable not defined error”.

    Any idea why? I just skip the Sheet1 or reference to the range by Worksheets(“Sheet1”), but I don’t understand why it doesn’t seem to be working.

    1. Hi Jakub,

      You need to use the quotes

       "A1"
      

      instead of

       “A1”
      

       
      Also ensure there is a worksheet with the code name Sheet1.

      Regards
      Paul

  3. I have 2 worsheets.sheet1 named account sheet2 is invoice named,i want to copy n paste by every i put invoice num in sheet2 cell A8,it will copy from sheet invoice F32 n paste in sheet1 start col E7 automatically,could you please help?

  4. Paul, absolutely fantastic. A great building block to start with – I am looking forward to later tutorials.

    John

    1. Hi Karel,

      Almost all the code goes in the modules. The worksheet modules contain the events and they should have minimal code.

      Paul

  5. Very pleased with how clearly you simplify a very complicated subject. thanks for “Dumbing it down” for us old folks

  6. Excellent.. this is what most people are looking forward to learn while practice. Hope to see more practical base in later tutorial by you. Hats off sir !!!

  7. Thanks for your response. Can you brief about your later tutorials atleast? like the tutorial 2 will contains loops and what more tutorials & contents you are planning.. Your first tutorial is awesome, none in this web world has prepared such tutorial with lots of practical activities topic/subject wise and atlast you put all we have learned in a single assignment at the end. Great !

    1. Thanks for your enthusiasm Pradeep.
      I only have a rough outline of actual content of future tutorials. I will know more of the future content as I create each one.

      My aim is that someone can learn VBA from scratch following these tutorials in order. This is the plan I working with.
      When I create a tutorial I have a starting outline but this always changes considerably as I go through it.

      Regards
      Paul

  8. Thanks for your thoughts on learning VBA from Scratch for non coders like me. Waiting for your Tutorial 2 soon.

  9. Hi Paul.. any idea when are you planning to add your tutorial 2 .. hope so you would link your tutorial activities within your 5 real time application that you explained earlier.

  10. Hi,
    I have 50 cells to be copied not in a single column or row and needs to be pasted in a single row.
    Say we have cells A1, A3, C2, D3, D24, E5,A10, ……. needs to be copied from sheet and pasted in different sheet in single row say in row 2 of sheet to.
    Thanks in advance.
    Regards
    Santosh

    1. You can use an array to do this. You will have to add the cells one by one to the array.

      Then you can write the array to the range e.g. row 2

      Sheet1.Range(“A2:Z2”) = arr

  11. Great tutorial – keep up the good work. Really easy to follow.

    Is it possible to be put on a mailing list as new tutorials are uploaded?

    1. As an aside, in the “double with” statement above, why is the “sheet1” needed in the second line for the last range but not elsewhere?

  12. Great job Paul…. well just wanted to bring to your kind attention…. that Activity 5….. Its mentioned as “Run the code in the sub(F5). Cells on Sheet2 should have the values as follows:
    C1 20, C2 100 and C3 1600” ………………..I think C should be changed to A since in the macro you mentioned refers to A1 20, A2 100, A 3 1600….when we run this Column A1 to A3 is what is displayed……….. I am also awaiting your second tutorial, please send a mail……….All the best…..

    1. Thank’s Paul for pointing that out. That was a typo. I’ve updated the post.

      I have created the second and third tutorial. They will be made available as part of membership contents of the site.

      This is currently undergoing testing. I will send more details to my email list when I have them.

      Regards
      Paul

      1. Oh..great to hear that….. well hope you will include me too in that email list. Thanking you in advance…….Your explanation is so excellent……Keep going…..All the best…..

    1. It is done in a similar way. You must first you must get the workbook and then the worksheet from the workbook.

      Sub UseDifferentWorkbook()
          
          ' Open workbook
          Dim wk As Workbook
          Set wk = Workbooks.Open("data.xlsx")
          
          ' Get worksheet
          Dim sh As Worksheet
          Set sh = wk.Worksheets("sheet1")
          
          ' Copy value
          sh.Range("A1") = Sheet1.Range("C1")
          
          ' Close workbook when finished
          wk.Close
      
      End Sub
      

      You can read more about this here: Excel VBA Workbook and Excel VBA Worksheet.

        1. Copying using the Range assignment is the same as using an array.

          e.g.

          Range("A1:A100").Value = Range("C1:C100").Value
          
          Dim arr As Variant
          arr = Range("C1:C100").Value
          Range("A1:A100").Value = arr
          
  13. Hi, Paul,
    I practice Double with. VBA shows the error message.
    Code:

    Sub DoubleWith()

    With Sheet3
    With WorksheetFunction
    .Range(“E1:H1”) = .Transpose(.Range(“A1:A4”).Value)
    .Range(“L1:L4”) = .Transpose(.Range(“E1:H1”).Value)
    End With
    End With

    End Sub
    Error message:
    Object doesn’t support this property or method (Error 438)

    The code statement is same as yours.
    I don’t know how to fix it.
    Please help me, thanks.

    1. You cannot use a “Double with”statement like this. When VBA meets a full stops it refers to the last With statement.
      So here it will put WorksheetFunction in from of .Range.

  14. Sir please help me on how to sort columns which has formulas in it…i have a column who picks value from other columns using vlookup function and this formula has to there…i have written vba code which only sorts values but not values which are derived from formulas…can you guide me…the only way i think is to copy whole sheet to new sheet and paste it as values then apply sort function..is there any other way…thank you in advance

  15. I’ve been browsing through VBA tutorials and none come even close to this one. VBA coding is explained in a logical and straight forward way so that newcomers can easily understand why and how each element is used in VBA.

    I’m eagerly looking forward to the following tutorials! Any idea when you plan to publish them?

  16. Great job on the Tutorial … Just wanted to bring to you attention on the assignment line 69 you reference the range A1:K1, I believe this should be A1:J1 as in the the answer otherwise the ranges are not equal and K1 will be #N/A error. Also in the range D2:D11 areas on shCountries and in the answer it references the population range of E2:E11. Thank you for making these tutorials available.

Leave a Reply

Your email address will not be published. Required fields are marked *