VBA Example - Generate an Excel table

Suppose you want to make a table of sales of your company in each regions in Quarter 1 and 2, like below.


This code will achieve it.

Sub Make_table()
    Sheets("Sheet1").Cells(1, 1) = "Region"
    Sheets("Sheet1").Cells(2, 1) = "East"
    Sheets("Sheet1").Cells(3, 1) = "West"
    Sheets("Sheet1").Cells(4, 1) = "South"
    Sheets("Sheet1").Cells(5, 1) = "North"
    Sheets("Sheet1").Cells(1, 2) = "Quarter 1"
    Sheets("Sheet1").Cells(1, 3) = "Quarter 2"
    Sheets("Sheet1").Cells(2, 2) = 52
    Sheets("Sheet1").Cells(3, 2) = 47
    Sheets("Sheet1").Cells(4, 2) = 68
    Sheets("Sheet1").Cells(5, 3) = 75
    Sheets("Sheet1").Cells(2, 3) = 89
    Sheets("Sheet1").Cells(3, 3) = 65
    Sheets("Sheet1").Cells(4, 3) = 79
    Sheets("Sheet1").Cells(5, 3) = 100
    MsgBox ("done")
End Sub

You may say that for this simple table, using VBA is so cumbersome, I would rather fill it manually! That's true. The merit of this method is that if you can read data from other data sources such as Access or SQLServer, then the whole process can be automated.

Comments

Popular posts from this blog

Excel - IF function

Excel - VLOOKUP function

Excel - Hierarchical chart (Treemap)