Trending February 2024 # Vba Variables, Data Types And Dim # Suggested March 2024 # Top 2 Popular

You are reading the article Vba Variables, Data Types And Dim updated in February 2024 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 Vba Variables, Data Types And Dim

VBA Variables, Data Types and Dim

Declaring variables using the various data types in VBA

Written by

CFI Team

Published August 8, 2023

Updated June 27, 2023

Declaring VBA Variables using Dim

This guide breaks down VBA variables, Data Types, and Dim. Typically, the very first step after naming your macro is declaring your variables. Variables are names for different pieces of the data that the macro will be working with. However, this sometimes proves difficult since it’s hard to plan ahead how many variables will be used in the macro. Eventually, when the macro is written, the user may add or remove certain variables. This will become more apparent further into this guide to writing VBA macros.

The very top of each macro after the sub name is a section called the declarations. Here, the user lists and names all the different variables he or she will use, and declares their data types. This is done by using the “Dim” statement. The “Dim” statement is followed by the name of the variable, and sometimes the statement “as [datatype]”. For example, if we wanted to create a variable for a Stock Price, we could write “Dim stockPrice as double”. This creates a variable called the stockPrice, which takes on the data type double. A double data type is one of the data types that allows for decimals, as opposed to the integer data type.

It’s not necessary to always declare the data type. Sometimes, it’s sufficient to declare the name, and VBA can infer the data type when the variable is used in the code later on. However, it’s generally safer to declare the data type you expect to use.

Each declaration will take its own line. It’s helpful to group variables of the same data type together.

Variable Data Types

There are quite a few VBA data types, but for the general purposes of financial modeling not all of them are used.

Below is a list of common VBA variables (known as data types) used in macros and their purposes:

Integer: Used to store number values that won’t take on decimal form.

Single: Used to store number values that may take on decimal form. Can also contain integers.

Double: A longer form of the single variable. Takes up more space, but needed for larger numbers.

Date: Stores date values.

String: Stores text. Can contain numbers, but will store them as a text (calculations cannot be performed on numbers stored as a string)

Boolean: Used to store binary results (True/False, 1/0)

Again, there are other data types, but these are the most commonly used for creating macros.

Storing a Value in a Variable

After a variable has been created, storing a value in it is simple.

Variable name = Variable value

String variable name = “Variable value”

(When using strings, you have to surround the text in quotation marks. This is not true for number or binary values)

Each named variable can only hold one value at a time.

Example of Declaring Variable Data types with Dim

Here is a break down of how to use Dim in VBA:

Declaring a company name variable: “Dim companyName as String”

Setting the company name variable:

companyName = “Tesla”

companyName = “Wells Fargo”

companyName = “No company name is available”

Declaring a variable to store net income: “Dim netIncome as Single” (or Double, depending on the scale)

Setting the net income variable:

netIncome = -5,000

netIncome = 0

netIncome = 1,000,000.64

Declaring a binary variable to store growth: “Dim isGrowthPositive as Boolean”

Setting the growth variable:

isGrowthPositive = True

isGrowthPositive = False

isGrowthPositive = 1 (same as True)

As you can see in the above example, these variables (and some extra variables to show grouping best practices) have been declared. Values have also been stored in the main variables. However, if this macro were to be run, it would simply store these values in the variables, and not use them in any way. To continue learning how to use variables, you need to know the VBA methods available to each one.

Additional Resources

Thank you for reading CFI’s guide to VBA variables, Data Types, and Dim. To keep learning and progressing your Excel skills we highly recommend these additional CFI resources:

You're reading Vba Variables, Data Types And Dim

Use Of Variables In Qlikview To Create Powerful Data Stories


An application with good Front-end and poor Back-end is like Beauty without brains. You are awed by it initially, but you get irritated by it over time. On the other hand, efficient Back-end with poor Front-end may not excite users to use the application. In today’s world, you need excellence on both the aspects.

Sadly, a lot of people associate data visualization with only front end engineering. In today’s article, I want to bring out what does Back end engineering look like in case of QlikView and how can it add tremendous power to your data stories.

The Natural progression in a programming language

If you have learnt coding on any language, you would have experienced this progression yourself.

The first stage of learning a language is to understand its syntax, ways to print output, doing mathematical calculations etc. At this stage, you typically don’t do any thing complex. This usually isn’t very exciting or helpful. After all you don’t learn a programming language to calculate 2 + 3!

The second stage of learning a language is when you start using variables to accomplish some of the more complex tasks. With use of variables, you can create generic logic, which are more complicated and useful. So it you want to compare 2 columns with a million numbers each, you can’t do that unless you use variables (May be you can, not me!). The beauty of the process is that once you learn use of variables, it is impossible to think that there was even a stage 1 involved in the learning process!

There are some more stages in learning a new programming language, but for today’s article we will focus on what I just mentioned as second stage of any programming language – the use of variables. If you are a complete newbie to QlikView, you should first learn the basics from our learning path – Resource to learn Qlikview from scratch and become an expert

Real life situation – variables to my rescue!

I started using QlikView some time in early 2012 and I fell in love with it. We had a team of passionate developers and over next 6 months (with a lot of dark nights), we were able to replace the traditional clunky excel / access reports on a nice QlikView dashboard for entire Sales process of our organization. We were now the envy of other Intelligence units in our organization and were quoted as a successful transition across the Organization.

In September 2012, the Sales Director called me. This was the time of sales planning for next year. So, I expected him to ask the plans for the same. And I was well prepared for this. Over years, we had created an Excel based application which would simulate a whole lot of scenarios and then spit out (literally) the targets for all the sales people.

Then came the bomb! The Sales Director said that this time he wants the planning to happen on our QlikView application. He said that he wanted a new sheet in our dashboard, where the sales people could enter parameters for their efforts (e.g. Taking 10 sales calls a day) and the application provides an estimate of where they would end taking seasonality and past trends in account.

I had no clue how to do this in QlikView, so I just listened to him. I didn’t want all the efforts from last 6 months to end and the people to go back to older ways of running business intelligence. Thankfully, I came across variables and their use to run what-if scenarios, which we went on to build in our application.

What is a Variable? What are the methods to create it?

Variables store data (static or calculated) of any type (numbers, string, boolean, float) and get referenced using expressions or directly by using its name. There are a few ground rules of variable naming convention in QlikView:

Rule 1: Whenever we create a variable for static value, we prefix variable name with “v” (lowercase).

Rule 2: Whenever we store an expression in a variable, we prefix variable name with “e” (lowercase).

After the first character, we should keep relevant names so that it is developer friendly. There are various methods to create a variable. The commonly used are:

Method 2: By using SET and LET statements.

Let’s look at them one by one:

Method 1:

Note: You can define a variable with an expression also.

Method -2:

This is because, these are the variables that QlikView creates using Set Statement. You can also use “Set” statement for defining variable(s) in script.

Let’s see how do we do it. Look at the below syntax of defining variable:

Syntax: Set Variable_Name=Value; Example: Set vPrevYr='2014';

Another method of variable creation is using “Let” statement. Let statement evaluates the expression on the right side of ‘=’ and assigns it to the variable on the left side of ‘=’.

Syntax: Let Variable_Name=Expression;

Example: Let vTest=5+8;

If you will use Set statement to store expression output in a variable, it will store the expression as a value. I’ll show the detailed effect of defining a formula with Let and Set statement in the coming up sections.

Example: Set vTest1=5+8;

In the screenshot below, you can see all the defined variables(vPrevYr, vTest, vTest1) after running script. Similarly, new variables can also be defined / found here.

Also Read: How to implement incremental load in qlikview?

How can we access variable?

The value of a variable can be accessed using equals (=) sign. If the variable is prefixed with equals ‘ = ‘ sign, QlikView tries to evaluate the value as a formula (QlikView expression) and then displays or returns the result rather than the actual formula text.

Let’s understand it by accessing above created variable “vTest” (created using Let) and “vTest1” (Created using Set).

Let’s create a text box object and put an expression as “=vTest” and similarly in another text box, we put “=vTest1” (as shown below).

Just notice that, the variable (vTest) created using “Let” has got evaluated well. On the contrary, variable (vTest1) created using “Set” has not been evaluated. This is the difference between creating a variable using Set or Let statement.

Now, to evaluate variable vTest1, we can use Dollar Sign Expansion (DSE). It is method to evaluate a formula. Let’s look at this method of using dollar sign expansion. Also, this is also a standard way of accessing a variable in QlikView.

Syntax: $(variable_Name)

Also Read: The concept of synthetic keys in Qlikview – Simplified !

What are most Common Uses of variable(s)?

Variables are the mainstay of data visualization softwares like Qlikview, chúng tôi etc. Optimizing the use of variables always reduces application development time. Let’s look at the some common uses of variables:

Portability: Variables are used when we want to store values and use them in multiple objects / charts without wanting to type those values again. Variables are also used when we want to perform dynamic calculations. For example: A variable created for representing previous year as “vPrevYr=$(=Max (Year)-1)”, refers to a dynamic calculation as per current selection and can be accessed by all objects of the document.

Use in Chart Objects: We can make use of variables in charts at multiple places using:

Conditional enable or disable dimension / expression / object:

 Think of a scenario where you have segregated your charts objects in two categories. Then, you want to show only one category at a time. This can effortlessly be done using button or variable. Let’s follow the below steps to perform this:

Step 1: Create a variable “


” and assign the value as zero (0).

Step 3: Assign the value to variable as zero (0) and provide the name to variable as “Category1”. Similarly create another variable as “Category2” and assign the variable (vVisible) value as 1.

What-if analysis: We can use variable in what if analysis expression also using “Input Box” or “Slider Object”. In such cases, we take value of variable from these objects (Input, Slider) and used them in expression.

Apart from the uses mentioned above, we can also use variable for incremental data load and in various scripting methodology to improve our data models.

End Notes:

In this article, we looked at the importance of variables, methods to create it and the common uses of variable in daily development. Basically, we have looked at two methods (Set & Let and Variable Overview) to create them.

If you like what you just read & want to continue your analytics learning, subscribe to our emails, follow us on twitter or like our facebook page.


Need And Types Of C++ Formatter

Definition of C++ Formatter

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Need of C++ Formatters in Source Code

Let us understand the need for C++ formatters with the help of an example:


using namespace std; intmain() { int num1, num2, add; cout<< “Enter the first integer”; cout<< “Enter the second integer”; add = num1 + num2; cout<< “The result is ” <<add ; return 0; }

The above code is the simple addition of 2 integer numbers. But how it is written makes it very uneasy or difficult to understand. There is a need for proper indentation and required spaces in the code. Code after ‘{‘ should be written and should be indented properly to show that the required block of code is a part of it. It should be formatted as given below:

using namespace std; intmain() { int num1, num2, add; cout<< “Enter the first integer”; cout<< “Enter the second integer”; add = num1 + num2; cout<< “The result is ” << add; return 0; }

Types of C++ Formatters

There are a lot of formatters / beautifiers available in the market. Let us understand some of the commonly used formatters in detail:

1. Clang-Format

Clang format is one of the most popular open-source formatters used to format C, C++, and Objective C source code. It automatically formats the C++ code and helps better understand the code. To format the source code automatically according to Electron C++, we need to run the following command:

clang-format -i

Users can also perform the formatting of code according to the specific requirements (other than the one available by default) by inserting the style in ‘.clang-format’ file or using the option -style = “{key:value, ….}”.

2. PrettyPrinter 3. Jindent

It automatically indents the code according to the syntax and correct coding conventions, which helps in finding the bugs in the code and saves time. One of the cool features of Jindent is that it provides a plugin for almost all popular IDEs like Visual Studio, Eclipse, Netbeans, etc so that it can be used easily by the programmers/ testers working on them. It allows its invocation from the shell scripts. Jindent provides support for all the Operating systems is it Windows, Mac, or Linux. Jindent is very user-friendly as it provides the GUI so that the user can perform actions like formatting settings, changing the environment variables, etc, very easily.

4. Highlighter

It is very user-friendly and hence pretty simple to use. Users must copy the source code in the desired text field, choose the C++ language, and Style dropdown to have the required formatting. It provides other interesting features as well as one can also choose to see the line numbers on the left side of the code and can directly insert the source code in the HTML page without adding any external CSS and JavaScript file to it.

Conclusion – C++ Formatter

The above description clearly explains the various formatters/beautifiers available in the market used to format the source code of C++ programs. Proper formatting and indentation are a must while working on real-time projects as it helps in a clear understanding of code and finding the bugs and hidden errors easily, especially the syntactical ones. It helps the maintenance team also to maintain the code properly and proceed further accordingly.

Recommended Articles

This is a guide to C++ Formatter. Here we also discuss the definition and need for C++ formatters, along with various types and examples. You may also have a look at the following articles to learn more –

Defintion, Examples And Types Invested In Portfolio

What is Portfolio Investment

Portfolio investments are investments in a portfolio of assets, including stocks, bonds, securities, debentures, deposits, or other financial instruments/assets. These investments are primarily made with the expectation that they will yield good returns or capital appreciation (i.e.) an increase in the value of investments. Risk and returns are directly proportional (i.e.) the higher the risk, the higher the returns.

Start Your Free Investment Banking Course

Download Corporate Valuation, Investment Banking, Accounting, CFA Calculator & others


Portfolio investments are assets acquired with the intention of maximizing wealth or earning income/ profits from the investment. This is a passive investment, as there won’t be any direct ownership or active management of assets. This can be either long-term or short-term; investors choose their investments based on their risk appetite and time period (i.e.) Long term or short-term.

Mutual funds and institutional investors predominantly deal with these investments. In the same way, pension funds and sovereign funds also invest in portfolios with a conservative approach. Risk tolerance is an important factor in choosing portfolio investments.

Features of Portfolio Investment

Portfolio investments are diversified, which reduces the risk by allocating the investments across various financial instruments, business sectors, and categories.

Investors’ risk tolerance and investment goals matter a lot in portfolio investments.

Stocks and bonds are predominantly considered portfolio investments but also include investment assets, a strategic investment method.

Example of Portfolio Investment

Mr. A wants to invest in a portfolio with moderate risks and returns. So, Mr. A plans to invest in the below portfolio. US Govt bonds offer a 2% yield of return per annum. This is a risk-free investment as the US Government provides it; at the same time, returns are also low. Blue-chip stocks offer around a 10% yield of return per annum. Dealing with equities always has risks, and the investments are not secured. So, the risk and returns both are high.

To have a moderate risk and returns, it is better to invest 50% in US Govt bonds and 50% in stocks, so the risk is also reduced, and the returns are averaged at 6%. In this case, returns are better than bonds but less than stocks, and at the same time, the risk is also reduced. If Mr. A wants more returns or low risk, it must decide by him, and he can change the proportion of the portfolio according to his risk tolerance and expectations of return.

Types of Portfolio Investment

There are different types of portfolios and different strategies for portfolio investment. It is up to the individual investor or the portfolio managers to choose the portfolio strategy based on the risk appetite and time horizon.

1. Hybrid Portfolio

A Hybrid portfolio is a diversified portfolio with a mix of high-risk and low-risk securities. It means investment in equities where risk and returns are high and in some fixed income securities like bonds, deposits, etc., where the risk and returns are comparatively lower than equities.

2. Aggressive Portfolio

An Aggressive portfolio invests in high-risk securities that will yield higher returns. The prime aim of this portfolio is to gain more returns from the investments, and their risk tolerance is at the higher end (i.e.) the investor in this portfolio is willing to take more risk in return for better gains.

They choose to invest in companies in the early stages of development with potential growth opportunities. They use the right business strategies where the risk is comparatively higher, and the returns also will be higher.

3. Defensive Portfolio

A Defensive portfolio is an investment in stocks dealing with essential/necessary goods. These stocks do well both in good times and bad times (i.e.) Even if the economy is bad, these stocks will perform as they deal with essential goods like food products, healthcare, household goods, etc., which are necessary for survival. This portfolio has less risk as they focus on essentials and yield better yields.

4. Income Portfolio

An Income portfolio is an investment in fixed income securities and dividend payout stocks that generate a regular source of income. The prime focus is to earn income from the investment. (E.g.) Bonds, deposits, Real estate investment trusts (REIT), etc., generate regular income through interest, rental income distribution, dividends, etc. These are low-risk investments and suitable for risk-averse investors.

5. Speculative Portfolio

 What Amount Should be Invested in Portfolio?

The amount to be invested in the portfolio is at the discretion of the investors and the investment plan offered by the investment managers. There are monthly SIP plans and lump sum investments.

Portfolio Investment Management

Portfolio investment management is the process of selecting the stocks and securities for a portfolio and overseeing their performance, and managing the funds keeping in mind the investment goals, risk tolerance, and time period. It requires analytical and decision-making skills to choose the right stocks for investments. The portfolio manager strategically takes the buy and sell call of stocks and aims to generate maximum returns.


The investor can choose the investment proportion considering the risk tolerance, return expectations, and time horizon.

Diversification of investments into different financial instruments helps to reduce risk and yield better returns.

Liquidity and flexibility exist in portfolio investment as the investor can exit from any particular investment at any time, and the remaining investment in the portfolio can be maintained.

Portfolio investments help to choose both fixed-income securities and capital appreciation investments. An Investor can choose the proportion of investment based on the strategic investment plan.

It is tough to track investment-related information constantly as the investments are diversified.

Proper securities and risk profile analysis needs to be carried out before making portfolio investments; otherwise, it may deliver desired returns.

It is tough for any individual investor to decide on a portfolio as it requires a lot of research and analysis; hence it creates a dependency for investors to rely on portfolio investment managers.

Financial knowledge is a must for investors to invest in portfolio investments.


Portfolio investments are good for those who want to balance their risk and returns and those who want to diversify their investments. The portfolio offers customization and helps investors to choose investments according to their risk tolerance, time horizon, and yield of returns. These services are offered by investment managers and other financial institutions that research and analyze securities and offer investment plans.

Recommended Articles

Overview Of Aws Database And Its Types

The term database alludes to an assortment of information that is usually coordinated and organized as tables or assortments. These tables or assortments can have various qualities characterized in the sections or archives, and we need to set the qualities against these properties in the lines or key-value pairs. An information base is outfitted with a database management system (DBMS), essentially a foundation programming application liable for overseeing tasks over the information inside a data set. Utilizing DBMS, you can play out all CRUD (create, read, update, delete) procedures on your database.

AWS Database

Amazon Web Services give a wide variety of database answers for its clients. Contingent on the idea of the information and the expense limitations of the client, these different data set types serve all clients likewise. AWS is a bunch of cloud administrations given by Amazon, which likewise gives different information bases as a component of its administration suite. These databases permit clients to assemble use-case-explicit information models, including a social diagram, wide-segment, etc. AWS deals with these data sets, liberating clients from undertakings, such as server provisioning, fixing, and reinforcement, which are inconceivably tedious.

Types of AWS Databases Amazon Quantum Ledger Database (QLDB)

Amazon QLDB is a serverless data set that gives programmed versatility, is not difficult to set up, and incorporates checking capacity. Quantum record information bases are renowned for giving permanence, straightforwardness, certain exchange logs, and history. The utilization cases can be banking exchanges, production network frameworks, enlistments, or anything requiring putting away history and logging records.

Amazon Aurora

Aurora is an AWS-claimed innovation that offers help for either MYSQL or PostgreSQL. It is costly compared with other RDS data sets yet gives better execution regarding accessibility, versatility, and read imitations. It can likewise give programmed monitoring facilities, backups, and instantaneous fail-over. In different capacities, you can utilize our Aurora serverless, Aurora multi-expert, and Aurora worldwide.

Amazon Timestream

It is a time series-based database, which is planned and upgraded to store time series in key-esteem matches. It can follow all information properly aligned grouping, which is restricted in normal social data sets. It is completely serverless and simple to send without overseeing a complex foundation. It is explicitly intended for various IoT tasks to gather sensor information in cutting-edge IT frameworks. It is fit for taking care of an exceptionally huge number of solicitations daily.

Amazon Redshift

It is a quick and completely overseen information stockroom administration in the cloud. Amazon affirms that the Redshift information warehouse centre conveys multiple times quicker execution than different information stockrooms using AI procedures. The Redshift information warehouse centre can be increased to a petabyte or more according to the prerequisites.

Amazon Keyspaces

This is a completely overseen and serverless database application for Apache Cassandra and makes it simple to send Apache Cassandra. It is a non-social data set with a wide-section mapping. It uses Cassandra Query Language (CQL) to perform the tasks of the data set. It additionally gives programmed scaling as per application traffic reaction. It is profoundly accessible, can handle countless demands, and guarantees security.

Amazon Neptune

This is explicitly intended for the visual portrayal of information utilizing diagrams. You can run custom analyses on various datasets and show results on the dashboards as diagrams. The assistance gives multi-zone accessibility, read replication, encryption, reinforcement, and recovery. The utilization cases can be checking network security, investigating the consequences of an AI calculation, or some other performance matrix.

Amazon DocumentDB

It is a NoSQL database and has a reported pattern. It utilizes the JSON configuration to store information in the data set. It is completely viable with MongoDB. So if you have any application running with MongoDB, you can rapidly move it to AWS DocumentDB. It is a serverless contribution by AWS, so it can scale naturally, as required. The main highlights are understood copies, programmed fall flat over capacity, well-being checking, reinforcements, depictions, and information encryption.

Amazon RDS

It is an overseen database help given by AWS, and it isn’t itself a data set. All things being equal, it empowers you to run different social data sets as needed. The RDS will convey the data set, database security and accessibility, network, versatility, read copies, backup, and maintenance. It will keep your database financially effective.

Amazon ElastiCache

Amazon ElastiCache is a completely overseen reserving administration that offers superior execution and practical and versatile string arrangements. Amazon ElastiCache gives two storing motors, specifically, Memcached and Redis.

Response Time − ElastiCache diminishes the reaction time by recovering information from a quick in-memory framework. It diminishes the reliance on circle-based data sets, which are normally slower.

Scalability − Amazon ElastiCache is intended to have the option to adjust itself naturally, and it can scale out or increase contingent upon the fluctuating app prerequisites.

Complete Management − Amazon ElastiCache is completely made due, so the normal authoritative errands, for example, equipment provisioning, disappointment recuperation, reinforcements, and more, are robotized.

Amazon DynamoDB

It is a non-social or NoSQL data set, so it isn’t great to run joins and connections between tables given key-esteem matches. It is a completely serverless help by AWS, so you don’t need to stress over scope quantification and scaling, and it can deal with a huge number of solicitations. It additionally gives security, encryption, worldwide accessibility, reinforcement, and reserving skills.


Excel Vba Select Case Statement

Case Value_1 Code Block when Test_Expression = Value_1 Case Value_2 Code Block when Test_Expression = Value_2 Case Value_3 Code Block when Test_Expression = Value_3 Case Else Code Block when none of the case conditions are met Dim UserInput As Integer UserInput = InputBox(“Please enter a number between 1 and 5”) Select Case UserInput Case 1 MsgBox “You entered 1″ Case 2 MsgBox “You entered 2″ Case 3 MsgBox “You entered 3″ Case 4 MsgBox “You entered 4″ Case 5 MsgBox “You entered 5″ End Select Dim UserInput As Integer UserInput = InputBox(“Please enter a number”) Select Case UserInput Case Is < 100 MsgBox “You entered a number less than 100″ MsgBox “You entered a number more than (or equal to) 100″ End Select Dim UserInput As Integer UserInput = InputBox(“Please enter a number”) Select Case UserInput Case Is < 100 MsgBox “You entered a number less than 100″ Case Else MsgBox “You entered a number more than (or equal to) 100″ End Select Dim UserInput As Integer UserInput = InputBox(“Please enter a number between 1 and 100”) Select Case UserInput Case 1 To 25 MsgBox “You entered a number less than 25″ Case 26 To 50 MsgBox “You entered a number between 26 and 50″ Case 51 To 75 MsgBox “You entered a number between 51 and 75″ Case 75 To 100 MsgBox “You entered a number more than 75″ End Select Dim StudentMarks As Integer Dim FinalGrade As String StudentMarks = InputBox(“Enter Marks”) Select Case StudentMarks Case Is < 33 FinalGrade = “F” Case 33 To 50 FinalGrade = “E” Case 51 To 60 FinalGrade = “D” Case 60 To 70 FinalGrade = “C” Case 70 To 90 FinalGrade = “B” Case 90 To 100 FinalGrade = “A” End Select MsgBox “The Grade is ” & FinalGrade End Sub

The above code asks the user for the marks and based on it, shows a message box with the final grade.

In the above code, I have specified all the conditions – for marks 0 – 100.

Another way to use Select Case is to use a Case Else at the end. This is useful when you have accounted for all the conditions and then specify what to do when none of the conditions is met.

The below code is a variation of the Grade code with a minor change. In the end, it has a Case else statement, which will be executed when none of the above conditions are true.

Sub CheckOddEven() Dim StudentMarks As Integer Dim FinalGrade As String StudentMarks = InputBox("Enter Marks") Select Case StudentMarks Case Is < 33 FinalGrade = "F" Case 33 To 50 FinalGrade = "E" Case 51 To 60 FinalGrade = "D" Case 60 To 70 FinalGrade = "C" Case 70 To 90 FinalGrade = "B" Case Else FinalGrade = "A" End Select MsgBox "The Grade is " & FinalGrade Dim FinalGrade As String Select Case StudentMarks Case Is < 33 FinalGrade = "F" Case 33 To 50 FinalGrade = "E" Case 51 To 60 FinalGrade = "D" Case 60 To 70 FinalGrade = "C" Case 70 To 90 FinalGrade = "B" Case Else FinalGrade = "A" End Select GetGrade = FinalGrade CheckValue = Range("A1").Value Select Case (CheckValue Mod 2) = 0 Case True MsgBox "The number is even" Case False MsgBox "The number is odd" End Select Select Case Weekday(Now) Case 1, 7 MsgBox "Today is a Weekend" Case Else MsgBox "Today is a Weekday" End Select Select Case Weekday(Now) Case 1, 7    Select Case Weekday(Now)    Case 1       MsgBox "Today is Sunday"    Case Else       MsgBox "Today is Saturday"   End Select Case Else MsgBox "Today is a Weekday" End Select Dim Department As String Department = InputBox("Enter Your Department Name") Select Case Department Case "Marketing" MsgBox "Please connect with Bob Raines for Onboarding" Case "Finance" MsgBox "Please connect with Patricia Cruz for Onboarding" Case "HR" MsgBox "Please connect with Oliver Rand for Onboarding" Case "Admin" MsgBox "Please connect with Helen Hume for Onboarding" Case Else MsgBox "Please connect with Tony Randall for Onboarding" End Select End Sub

Hope all the examples above were helpful in understanding the concept and application of Select Case in Excel VBA.

You May Also Like the Following VBA Tutorials:

Update the detailed information about Vba Variables, Data Types And Dim on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!