Open In App

Programming Charts in Excel VBA

Last Updated: 11 Nov, 2022

P

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

VBA stands for Visual Basic for Applications and it is developed by Microsoft. MS Excel and many other Microsoft applications like word, access, etc have this language integrated into them using which one can do various things. VBA can be used in MS Excel through the code editor in its developer tab through which one can generate various types of charts and user-defined functions, connect to windows APIs, and much more. 

Enabling the Developer Tab in Excel

To use VBA in excel first of all we will need to make the developer tab visible as it is not visible as default when it is installed. We can do this by following the steps below:

Step 1: Click on the file option in the top left corner.

Clicking-file-option

 

Step 2: Click on the options tab in the bottom left corner which will take you to excel options.

Clicking-options-tab

 

Step 3: Then click on the customize ribbon option and check the developer tab in the options available.

Clicking-customize-ribbon

 

Table of Data for Charts

The table of data that I used for generating the chart is a small table containing the marks of students in different subjects. The table is shown below:

Dataset

 

Programming Charts in Excel VBA

To produce charts from the data table present in our sheet first we need to create a command button by clicking which we will generate the desired chart that we programmed in the VBA. To do so just select the developer tab and then select insert then from ActiveX Controls choose the command button then place it anywhere in the sheet.

Choosing-command-button

 

After placing the button in the sheet double click the button, if it doesn’t work then click the design mode option in the developer tab and then double-click on the button. It will take you to the VBA Editor where it will open starting with the function that handles the click function of the button you just created.

VBA-editor-opens

 

To increase the font size in the VBA Editor go to the tools tab and then the options tab and then to the editor format tab and increase the font size to your desired size. After we got our button and adjusted the font size its time to write some programs to create charts using those buttons and data tables in the sheet. Below is a VBA Code that runs when the user clicks the command Button. Remember to change to design mode to go to the editor when you click the button and turn off the design mode when you want to see the click function in action.

Private Sub CommandButton1_Click()

Dim bar_graph As ChartObject

Set bar_graph = ActiveSheet.ChartObjects.Add(Top:=Range(“E4”).Top, Left:=Range(“E4”).Left, Width:=400, Height:=300)

bar_graph.Chart.SetSourceData Worksheets(“Sheet1”).Range(“A2:C8”)

bar_graph.Chart.ChartType = xl3DColumn // Here you can choose from a variety of chart types

Worksheets(“Sheet1”).Cells(1, 1).Select // Optional

End Sub

Let’s Understand the code written above in Excel VBA:

  • In the above code Lines from Private Sub CommandButton1_Click to End Sub defines the Click function on the button.
  • Dim refers to Dimension and it is used to declare variables in Excel VBA. 
  • Above we used variable bar_graph as type ChartObject. ChartObject contains all the sheets in the workbook (i.e, both chart sheets and worksheets).
  • We then set the ActiveSheet where the chart will be drawn such that its left and top corner is the E4 cell just to make sure the chart appears as close to the button and data table as possible.
  • The width and Height define the width and height of the chart that will be generated.
  • The chart is the function that helps create and change the type of chart in the ActiveSheet.
  • We set the source data for the chart with the help of SetSourceData and give it the data from Range A2 to C8 from Sheet1.
  • Using the ChartType function we can choose any kind of chart that we want to generate from the number of charts available in the list. The list of charts pops up automatically when one writes “Chart.ChartType =” in the VBA Editor.
  • The last line of code is optional and selects the A1 cell after completing the function which is just the Title of the table.

There are many other ways to write the same code in Excel VBA and I have shown just a single way. With the help of variables for every function and using the keyword to change their attributes can be learned easily if one learns how to write VBA in a better way. 

VBA-command

 

Output of Chart Function

When the command button is pressed outside the design mode, the chosen chart is displayed in the cell range mentioned in the code above like the picture shown below.

Output-of-chart-function

 



P

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

Generating Dynamic Charts With VBA in Excel

article_img
A powerful graph range is an information range that refreshes naturally when you change the information source. This unique reach is then utilized as the source information in an outline. As the information changes, the powerful reach refreshes right away which prompts an update in the outline. The following is an illustration of a graph that utilizes a unique outline range. Sample Data Follow the further steps in Generating Dynamic Charts with VBA in Excel Step 1: Opening the Visual Essential Window. Press ALT+F11 on your console to open the Visual Essential Window. Step 2: Embedding Another Module. Go to the Addition > Module choice in the toolbar. Click on Module. Another module called Module1 will be embedded. Step 3: Putting the VBA Code sub create _dynamic_ chart () Application . ScreenUpadting = False with Activesheet. shapes ( Application .caller ) .Fill.Forecolor If . Brightnesss = 0 Then . Brightness = -0.150000006 Else . Brightness = 0 End If End With Dim Sequence ( ) As String Desired__shapes = Array ( " Rounded Rectangle 1" , " Rounded Rectangle 2 " , " Rounded Rectangle For i = LBound ( Desired _Sh
Read More

How to Create Charts in Excel Using Worksheet Data and VBA?

article_img
Excel is an important software provided by Microsoft Corporation. This software belongs to one of the major software suites Office 365. In this software suite, there are other software are present like Word, PowerPoint, etc. They are called Office 365, as this software are mostly used for office purpose. But now the world has changed a lot. After the Corona Pandemic, the world knows the positivity of using digital tools. Office 365 was not different from that. As a part of the software suite, Excel software also gains some importance from the users. They are not only used for official purposes. But they can also be used for school purposes. Excel is software that can able to store data in an effective form. So, searching for the data becomes more manageable in this software. Excel has another great feature. It can be used to derive the charts from the provided data. The charts are helpful for analyzing any growth of the data. If there are thousands of data present, it is a difficult task to extract some analysis from that data. But if those data are converted to charts, then it will be easy to analyze those data. Excel sheet helps to do the same. Charts can be prepared whatever the
Read More

How to Use Select Case Statement in Excel VBA?

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it's like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it's like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome. Syntax of the Select Case Statement of Excel VBAThe VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps
Read More

Excel VBA Concatenation Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in functions, operators, etc. Some helpful links to get more insights about concatenate and using VBA in Excel : Record Macros in ExcelCONCATENATE in ExcelHow to Create a Macro in Excel? In this article, we are going to see about concatenate operators and how to use VBA to concatenate strings as well as numbers. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs at the top of the Excel window.Now select Customize the Ribbon from the pop-down menu.In the Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now, we need to open the Visual Basic Editor. There are two ways : Go to Developer and directly click on the
Read More

Excel VBA Comparison Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Some helpful links to get more insights about Macros, VBA in Excel : 1. Record Macros in Excel. 2. How to Create a Macro in Excel? In this article, we are going to discuss various comparison operators in Excel VBA. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs in the top of the Excel window.Now select Customize the Ribbon from the pop-down menu. The Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now click on the Visual Basic option in the Developer tab and make a new module to write the program.Developer -> Visual Basic -> Tools -> Macros Now create a Macro and give any suitable name. This will open the Editor window where can write the code. Comparison Operators in Excel:S.No.OperatorsDefinition 1<> Not equal operator is
Read More

A

How to Use for Each Loop in Excel VBA?

A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to iterate through the elements of the collection or array. For collections, the element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, the element can only be a Variant variable.groupRequired(Must be mentioned). Name of an object collection or array (except an array of user-defined types).statementOptional (May or may not be mentioned). One or more statements are executed on each item in the group. There are 4 basic steps to writing a For Each Next Loop in VBA: Declare a variable.Write the For Each Line with the variable and collection references.Add line(s) of code to repeat for each item in the collection.Write the Next line to terminate the loop. The For…Each block is entered if there is at least one element in the group. Upon entering the loop,
Read More

A

How to Use Do While Loop in Excel VBA?

article_img
A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop Flowchart: Uses of Do-While loop: The Do While loop is used in two ways: Do…while loop which checks the condition at the STARTING of the loop.Do…while loop which checks the condition at the END of the loop. Syntax 1: Do While condition [statements] [Exit Do] [statements] Loop Syntax 2: Do While [statements] [Exit Do] [statements] Loop conditionImplementing a Do While loop: Follow the below steps to implement a Do-While loop: Step 1: Define a Macro Private Sub Demo_Loop() End Sub Step 2: Define variables j=2 i=1 Step 3: Write Do While Loop. You can write condition at the beginning or at the end Do While i < 5 Step 4: Write statements to be executed in loop msgbox "Table of 2 is : " & (j*i) i=i+1 Step 5: End loop. Now let's take a look at some of the examples. Example 1: Do…while loop which checks the condition at the STARTING of the loop. The below example uses Do…while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True
Read More

How to Use For Next Loop in Excel VBA?

article_img
If you are familiar with the programming you must have an idea of what a loop is, In computer programming, a loop is a sequence of statements that are repeated until a specific condition is satisfied. In Excel VBA the "For Next" loop is used to go through a block of code a specific number of times. Syntax: For counter = start to end [step count] [code block to execute] statement 1 statement 2 statement 3 . . statement n Next [counter] Here we can use the counter or any other variable to run them as many times as we need. Example: When you are displaying numbers from 1 to 10 you may want to set the value of a variable to 1 and display it 10 times, increasing its value by 1 on each loop iteration. The same logic is used in VBA. We specify how many times we have to run the loop, and then specify what code should our loop execute each time the loop runs. A loop has 3 parts the first one is an initialization, the second is the condition under which the loop runs, and the last is increment or decrement. The flow of the control in for loop:The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.Then the second
Read More

How to Get Length of Array in Excel VBA?

article_img
We use UBound and LBound functions to get the length of an Array in Excel VBA. In this article, we will discuss them in detail. Syntax: UBound() function UBound (arrayname, [ dimension ]) Parameters: arrayname: required. Array variable namedimension: optional Returns: Return upper limit of an array dimension. Syntax: LBound() Function LBound (arrayname, [ dimension ]) Parameters: arrayname : required. Array variable namedimension : optional Returns: Return lower limit of an array dimension Sample Data: VBA Code to get the length of Array (one-dimensional array): Declare Variables: Declaring a customer array with the size of 10. Sub oneDimArrayLength() ' Array variable Declaration Dim customer (1 To 10) As String Assign values to array elements customer(1) = "ANTON" customer(2) = "BERGS" customer(3) = "BOLID" customer(4) = "KOENE" customer(5) = "FRANS" Use UBound function to get the size of an array and Message box to display the result 'Message box to popup length of 1D array MsgBox "Array has " & UBound(customer) & " element(s)." End Sub To Run VBA Code Press Alt+F8 to popup macro window. Select " oneDimArrayLength" and Click Run button. Output VBA Code to get the length
Read More
three90RightbarBannerImg