Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Excel Tutorial
  • Excel Formulas
  • Excel Shortcut Keys
  • Data Analysis in Excel
  • Formatting in Excel
  • Excel Workbooks
  • Statistical Functions
  • Data Visualization in Excel
  • Pivot Tables in Excel
  • MS Excel Quiz
  • Excel Interview Questions
  • Advance Excel
Open In App
Next Article:
How to Use Select Case Statement in Excel VBA?
Next article icon

How to Set Variable to Cell Value in Excel VBA?

Last Updated : 23 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Adding data to the worksheet is often done and it is essential to learn how to set variable to cell value in excel VBA. There can be instances when you want to add the same data to your worksheet. This task could easily be achieved with the help of Excel VBA variables. You can assign your cell values with variables. Let's learn how to set variables to cell values in Excel VBA.

Declaring Variables in VBA

Before learning the assignment of variables, one needs to know what are variables and why they are used? Like any other programming language, VBA has variables. Variables are the containers to store data in them. There are some rules for storing data in them.

Rules for naming Variables

  • The variable name cannot start with a number.
  • While naming the variables you cannot have space between the names which means a space character (' ') is prohibited.
  • The length of the variable name should be less than Two-hundred and fifty-five (255) characters.

Implicit and Explicit Declaration

In Excel VBA, variables can be classified into 2 categories implicit and explicit,

Implicit Declaration

The implicit declaration declares a variable of data type variant. When we create variables implicitly, we never mention the data type to be used. The VBA automatically considers that variable as of variant type.

Syntax: variable_name = assigned_value

The variant data type is of two types,

  • Numeric Variant: The numeric variant data type is provided by VBA when the variable is assigned with a number. The bytes used are 16. It can take any value to Double.
Numeric-variant-data-type
  • Text Variant: The text variant data type is provided by VBA when the variable is assigned with a text. The bytes used are 22. It's always possible to take variable sizes of the string.
Text-variant-data-type

Explicit Declaration

The explicit declaration declares a variable of custom data type. One can always mention the data type of the variable being used at the time of declaration. The keyword used is 'Dim'.

Syntax: Dim variable_name as data_type

variable_name = assigned_value

Variable-name-as-data-type

Opening VBA immediate Window

The excel immediate window can be compared with a terminal that displays the code output in any other programming language. We will use this immediate window to run our code in the macro itself and display the code output immediately. You can also use the immediate window for debugging and running multiple VBA macros at once.

Different Ways to Open Immediate Windows in VBA

Press Ctrl + G

Open your VBA, then use the Short cut Ctrl + G on your keyboard, and the immediate window will open at the bottom side of your VBA.

Using View Tab

Step 1: Go to the Developer Tab, under the code section, and click on Visual Basic.

Clicking-visual-basic

Step 2: The VBA editor is open now.

VBA-editor-opens

Step 3: Go to View Tab, and click on Immediate Window.

Clicking-immediate-window

Step 4: The Immediate Window appears.

Immediate-window-displayed

Set Variable to Cell Value

After learning how to declare variables, and how to access the immediate window, you are ready to learn how to set variables to cell Values. Given the name of a student, 'Arushi'. Write her Age and Aim in the worksheet by assigning variables in the VBA Macro.

Assigning-variables-in-VBA-macro

Step 1: Go to the Developer Tab, under the code section, and click on Visual Basic.

Clicking-visual-basic

Step 2: Your VBA editor is opened. Create a new Module. The name of the Sub created is geeks(). Declare an Age variable explicitly with custom data type as Integer. Assign the variable value as 19.

Variable-value-19-assigned

Step 3: Set the cell value by the variable name. Use =Range(cell).Value function to access any cell in the worksheet. Assign the Age variable to it. Run your macro.

Assigning-age-variable

Step 4: The value of cell C5 is set to 19.

Value-of-C5-set-as-19

Step 5: Repeat steps 2, 3, and 4 to set Aim for cell D5. Declare a variable name Aim explicitly with data type as Variant. Assign the variable value "CA". Again, use the range function and set the cell value of D5 to the variable Aim.

Setting-value-of-D5-to-variable-name

Step 6: The value of cell D5 is set to "CA".

D5-set-as-CA

Set Cell Value to Variable

We can also assign the cell values in the worksheet to the variables. Consider, the same data set as above but this time the age and aim of the student 'Arushi' are prefilled. Your task is to assign these values to the variables and print them in the immediate window.

Values-prefilled-shown

Step 1: Go to the Developer Tab, under the code section, and click on Visual Basic.

Clicking-visual-basic

Step 2: Declare the Age variable explicitly using the Dim keyword.

Age-variable-declared

Step 3: Assign the Age variable with the value of cell 'C5'. This can be achieved using =Range(cell).Value function. Print the Age variable in the immediate window using Debug.Print(variable) function.

Assigning-age-variable-to-C5

Step 4: Click on the run button. The macro will run, and 19 is printed in the immediate window of the VBA.

Running-the-macro

Step 5: Repeat Steps 2, 3, and 4. Declare the Aim variable explicitly. The Range function assigns a cell value of D5 in the variable Aim. Print the Aim variable in the immediate window.

Printing-aim-variable-in-window

Step 6: Click on the run button, and "CA" is printed in the Immediate Window.

CA-printed-in-immediate-window

Next Article
How to Use Select Case Statement in Excel VBA?
author
gautamgoel962
Improve
Article Tags :
  • Excel
  • News
  • Microsoft Office
  • Excel-VBA
  • ExcelGuide

Similar Reads

  • How to Use Select Case Statement in Excel VBA?
    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. Se
    10 min read
  • How to Create a Two-Variable Data Table in Excel?
    Two-Variable Data Table is a very significant tool for what-if data analysis. With the help of two-variable data tables, we can find all possible trends that can arrive by changing different values. For example, if we know the annual sales of a company, its percentage of expenses and growth. So, by
    2 min read
  • How to use If-Else Statement in Excel VBA?
    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 learn how to use the If Else statement in Excel VBA. Impl
    2 min read
  • VBA Subroutine in Excel - How to Call Sub in VBA?
    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 lea
    2 min read
  • How to Use Do While Loop in Excel VBA?
    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 S
    2 min read
  • How to use Do Until Loop in Excel VBA?
    In this article, we are going to see look into the Do Until loop in Excel VBA using a suitable example. 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-cli
    3 min read
  • How To Calculate Variance in Excel
    If you're looking to understand your data better, knowing how to calculate variance in Excel is a great skill to have. Calculating Variance in Excel is a Fundamental calculation that helps to measure the dispersion or spread of data points in a dataset. Luckily, Excel makes it easy to do this with s
    7 min read
  • Get, Set, or Change Cell value in Excel VBA
    VBA, or Visual Basic for Applications, is a programming language developed by Microsoft. It is used to automate repetitive tasks, enhance functionality, and create custom solutions within Microsoft Office applications like Excel, Word, and Access. VBA allows users to write scripts or small programs
    9 min read
  • How to Insert and Run VBA Code in Excel?
    In Excel VBA stands for (Visual Basic for Application Code) where we can automate our task with help of codes and codes that will manipulate(like inserting, creating, or deleting a row, column, or graph) the data in a worksheet or workbook. With the help of VBA, we can also automate the task in exce
    2 min read
  • How to use If-Else-If Statement in Excel VBA?
    In this article, we are going to look into how to use the If Else If statement in Excel VBA using a suitable example. 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 proce
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences