In this Article
- Set Cell Value
- Range.Value & Cells.Value
- Set Multiple Cells’ Values at Once
- Set Cell Value – Text
- Set Cell Value – Variable
- Get Cell Value
- Get ActiveCell Value
- Assign Cell Value to Variable
- Other Cell Value Examples
- Copy Cell Value
- Compare Cell Values
This tutorial will teach you how to interact with Cell Values using VBA.
Set Cell Value
To set a Cell Value, use the Value property of the Range or Cells object.
Range.Value & Cells.Value
There are two ways to reference cell(s) in VBA:
- Range Object – Range(“A2”).Value
- Cells Object – Cells(2,1).Value
The Range object allows you to reference a cell using the standard “A1” notation.
This will set the range A2’s value = 1:
Range("A2").Value = 1
The Cells object allows you to reference a cell by it’s row number and column number.
This will set range A2’s value = 1:
Cells(2,1).Value = 1
Notice that you enter the row number first:
Cells(Row_num, Col_num)
Set Multiple Cells’ Values at Once
Instead of referencing a single cell, you can reference a range of cells and change all of the cell values at once:
Range("A2:A5").Value = 1
Set Cell Value – Text
In the above examples, we set the cell value equal to a number (1). Instead, you can set the cell value equal to a string of text. In VBA, all text must be surrounded by quotations:
Range("A2").Value = "Text"
If you don’t surround the text with quotations, VBA will think you referencing a variable…
Set Cell Value – Variable
You can also set a cell value equal to a variable
Dim strText as String
strText = "String of Text"
Range("A2").Value = strText
Get Cell Value
You can get cell values using the same Value property that we used above.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Get ActiveCell Value
To get the ActiveCell value and display it in a message box:
MsgBox ActiveCell.Value
Assign Cell Value to Variable
To get a cell value and assign it to a variable:
Dim var as Variant
var = Range("A1").Value
Here we used a variable of type Variant. Variant variables can accept any type of values. Instead, you could use a String variable type:
Dim var as String
var = Range("A1").Value
A String variable type will accept numerical values, but it will store the numbers as text.
If you know your cell value will be numerical, you could use a Double variable type (Double variables can store decimal values):
Dim var as Double
var = Range("A1").Value
However, if you attempt to store a cell value containing text in a double variable, you will receive an type mismatch error:
Other Cell Value Examples
VBA Programming | Code Generator does work for you!
Copy Cell Value
It’s easy to set a cell value equal to another cell value (or “Copy” a cell value):
Range("A1").Value = Range("B1").Value
You can even do this with ranges of cells (the ranges must be the same size):
Range("A1:A5").Value = Range("B1:B5").Value
Compare Cell Values
You can compare cell values using the standard comparison operators.
Test if cell values are equal:
MsgBox Range("A1").Value = Range("B1").Value
Will return TRUE if cell values are equal. Otherwise FALSE.
You can also create an If Statement to compare cell values:
If Range("A1").Value > Range("B1").Value Then
Range("C1").Value = "Greater Than"
Elseif Range("A1").Value = Range("B1").Value Then
Range("C1").Value = "Equal"
Else
Range("C1").Value = "Less Than"
End If
You can compare text in the same way (Remember that VBA is Case Sensitive)
Key Notes
- The value property can be used in both ways (you can read and write a value from a cell).
- You can refer to a cell using Cells and Range Object to set a cell value (to Get and Change also).
To set a cell value, you need to use the “Value” property, and then you need to define the value that you want to set. Here I have used some examples to help you understand this.
1. Enter a Value in a Cell
Let’s say you need to enter the value “Done” in cell A1. In that case, the code would be something like the below:
Range("A1").Value = "Done"
As you can see, I have first defined the cell address where I want to add the value, and then the value property. In the end, I have assigned the value “Done” using an equal “=” sign enclosed in double quotation marks.
You can also use the “Cells” property, just like the following code.
Cells(1, 1).Value = "Done"
The above code also refers to cell A1.
Apart from this, there is one more way that you can use and that’s by not using the value property directly assigning the value to the cell.
Cells(1, 1) = "Done"
But this is recommended to use the value property to enter a value in a cell.
Now let’s say you want to enter a number in a cell. In that case, you don’t need to use double quotation marks. You can write the code like the following.
Range("A1") = 99
You can also DATE and NOW (VBA Functions) to enter a date or a timestamp in a cell using a VBA code.
Range("A1").Value = Date
Range("A2").Value = Now
And if you want to enter a value in the active cell then the code you need would be like:
ActiveCell.Value = Date
2. Using an Input Box
If you want a user to specify a value to enter in a cell you can use an input box. Let’s say you want to enter the value in cell A1, the code would be like this:
Range("A1").Value = _
InputBox(Prompt:="Type the value you want enter in A1.")
In the above code, the value from cell A1 assigns to the value returned by the input box that returns the value entered by the user.
3. From Another Cell
You can also set cell value using the value from another cell. Let’s say if you want to add value to cell A1 from the cell B1, the code would be:
Range("A1") = Range("B1").Value
You can also refer to cell B1 without using the value property.
Range("A1") = Range("B1")
4. Set Value in an Entire Range
Imagine you want to enter values in multiple cells or a range of cells instead of a single cell, in that case, you need to write code like the below:
Range("A1:A10").Value = Date
Range("B1, B10").Value = Now
In the first line of code, you have an entire range from cell A1 to A10, and in the second line, there are two cells B1 and B10.
Get Cell Value
As I said, you can use the same value property to get value from a cell.
1. Get Value from the ActiveCell
Let’s say you want to get the value from the active cell, in that case, you need to use the following code.
ActiveCell.Value = Range("A1")
In the above code, you have used the value property with the active cell and then assigned that value to cell A1.
2. Assign to a Variable
You can also get a value from a cell and further assign it to a variable.
Now in the above code, you have the variable “i” Which has the date as its data type. In the second line of the code, the value from cell A1 is assigned to the variable.
3. Show in a MsgBox
Now imagine, you want to show the value from cell A1 using a message box. In this case, the code would be like the below.
MsgBox Range("A1").Value
In the above code, the message box will take value from cell A1 and show it to the user.
Change Cell Value
You can also make changes to a cell value, and here I have shared a few examples that can help you to understand this.
1. Add a Number to an Existing Number
Let’s say if you want to add one to the number that you have in cell A1, you can use the following code.
Range("A1").Value = Range("A1").Value + 1
The above code assigns value to cell A1 by taking value from cell A1 itself and adding one to it. But you can also use VBA IF THEN ELSE to write a condition to change only when there is a number in the cell.
If IsNumeric(Range("A1").Value) Then
Range("A1").Value = Range("A1").Value + 1
End If
2. Remove First Character from Cell
Now, the following code removes the first character from the cell value and assigns the rest of the value back to the cell.
Range("A1").Value = Right(Range("A1").Value, Len(Range("A1").Value) - 1)
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- VBA Check IF a Cell is Empty + Multiple Cells
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
We use VBA to automate our tasks in excel. The idea of using VBA is to connect the interface of excel with the programming. One of the very most connections between them is by changing the cell values. The change in cell value by programming shows the power of VBA. In this article, we will see how to set, get and change the cell value.
Set Cell Value
Assigning a cell with a value can be achieved by very two famous functions in VBA i.e. Range and Cells function.
Range Function in VBA
The range function helps access the cells in the worksheet. To set the cell value using the range function, we use the .Value.
Syntax: Range(cell_name).Value = value_to_be_assinged.
Set the value to a single cell
If you want to assign ’11’ to cell A1, then the following are the steps:
Step 1: Use the Range function, in the double quotes type the cell name. Use .Value object function. For example, Range(“A1”).Value = 11.
Step 2: Run your macro. The number 11 appears in cell A1.
Set the value to multiple cells at the same time
Remember the days, when your teacher gives you punishment, by making you write the homework 10 times, those were the hard days, but now the effort has exponentially reduced. You can set a value to a range of cells with just one line of code. If you want to write your name, for example, “Arushi” 10 times, in the range A2 to A11. Use range function. Following are the steps:
Step 1: Use the Range function, in the double quotes, write “Start_of_cell: End_of_cell”. Use .Value object function. For example, Range(“A2:A11”).Value = “Arushi”.
Step 2: Run your macro. The text “Arushi” appears from cell A2 to A11 inclusive.
Cells Function in VBA
The Cells function is similar to the range function and is also used to set the cell value in a worksheet by VBA. The difference lies in the fact that the Cells function can only set a single cell value at a time while the Range function can set multiple values at a time. Cells function use matrix coordinate system to access cell elements. For example, A1 can be written as (1, 1), B1 can be written as (1, 2), etc.
Syntax: Cells(row_number, column_number).Value = value_to_be_assign
For example, you want to set the cell value to “Arushi cleared CA with Rank “, in cell B1. Also, set cell C1, to ‘1’. Following are the steps:
Step 1: Open your VBA editor. Use cells function, as we want to access cell B1, the matrix coordinates will be (1, 2). Type, Cells(1, 2).Value = “Arushi cleared CA with Rank” in the VBA code.
Step 2: To access cell C1, the matrix coordinates are (1, 3). Type, Cells(1, 3).Value = 1 in the VBA code.
Step 3: Run your macro. The required text appears in cell B1, and a number appears in C1.
Setting Cell values by Active cell and the input box
There are other ways by which you can input your value in the cell in a worksheet.
Active Cell
You can set the cell value of a cell that is currently active. An active cell is the selected cell in which data is entered if you start typing. Use ActiveCell.Value object function to set the value either to text or to a number.
Syntax: ActiveCell.Value = value_to_be_assigned
For example, you want to assign the active cell with a text i.e. “Arushi is practicing CA”, also want to change the color of the cell to yellow. Following are the steps:
Step 1: Use the ActiveCell object to access the currently selected cell in the worksheet. Use ActiveCell.Value function object to write the required text.
Step 2: Color the cell by using ActiveCell.Interior.Color function. For example, use vbYellow to set your cell color to yellow.
Step 3: Run your macro. The currently selected cell i.e. B1 has attained the requirements.
Input Box
You can use the input box to set the cell value in a worksheet. The input box takes the custom value and stores the result. This result could further be used to set the value of the cell. For example, set the cell value of A1, dynamically by taking input, from the input box.
Following are the steps
Step 1: Open your VBA editor. A sub-procedure name geeks() is created. Use the Range function to store the value given by the input box.
Step 2: Run your Macro. A dialogue-box name Microsoft Excel appears. Enter the value to be stored. For example, “geeks for geeks”. Click Ok.
Step 3: Open your worksheet. In cell A1, you will find the required text is written.
Get Cell Value
After setting the cell value, it’s very important to have a handsome knowledge of how to display the cell value. There can be two ways two get the cell value either print the value in the console or create a message box.
Print Cell Value in Console
The console of the VBA editor is the immediate window. The immediate window prints the desired result in the VBA editor itself. The cell value can be stored in a variable and then printed in the immediate window. For example, you are given a cell A1 with the value ’11’, and you need to print this value in the immediate window.
Following are the steps
Step 1: Press Ctrl + G to open the immediate window.
Step 2: The cell value in A1 is 1.
Step 3: Open your VBA editor. Declare a variable that could store the cell value. For example, Val is the variable that stores the cell value in A1. Use the Range function to access the cell value. After storing the cell value in the val, print the variable in the immediate window with the help of Debug.Print(val) function.
Step 4: Run your macro. The cell value in A1 is printed in the immediate window.
Print Cell Value in a Message Box
A message box can also be used to show the cell value in VBA. For example, a random string is given in cell A1 of your string i.e. “Arushi studies in Hansraj”. Now, if you want to display the cell value in A1, we can use Message Box to achieve this.
Following are the steps
Step 1: Open your VBA macro. Create a message box by using MsgBox. Use the Range(cell).Value function to access the cell value.
Step 2: Run your macro. A message box appears, which contains the cell value of A1.
Change Cell Values
The value, once assigned to the cell value, can be changed. Cell values are like variables whose values can be changed any number of times. Either you can simply reassign the cell value or you can use different comparators to change the cell value according to a condition.
By reassigning the Cell Value
You can change the cell value by reassigning it. In the below example, the value of cell A1 is initially set to 1, but later it is reassigned to 2.
Following are the steps
Step 1: Open your VBA code editor. Initially, the value of cell A1 is assigned to 1. This initial value is printed in the immediate window. After that, we changed the value of cell A1 to 2. Now, if we print the A1 value in the immediate window, it comes out to be 2.
Step 2: The immediate window shows the output as 1 and 2.
Changing cell value with some condition
We can use if-else or switch-case statements to change the cell value with some condition. For example, if your age is greater than 18 then you can drive else you cannot drive. You can output your message according to this condition.
Following are the steps
Step 1: A code is written in the image below, which tells whether you are eligible for a driving license or not. If your age is greater than 18 then cell A1 will be assigned with the value, “You are eligible for the driving license”, else A1 will be assigned with “You are not eligible for driving license”.
Step 2: Run your macro. An input box appears. Enter your age. For example, 19.
Step 3: According to the age added the cell value will be assigned.
Содержание
- VBA Ranges — Getting and Setting Cell Values
- Getting Cell Values
- What happens if you use .Value on a set of cells?
- How do you get a single cell from a set of cells?
- The Range.Cells Function
- Setting Cell Values
- How do you set multiple cells’ values?
- Getting and Setting Cell Values from a Named Range or Table Name
- What’s next?
- VBA Cell Value – Get, Set, or Change
- Set Cell Value
- Range.Value & Cells.Value
- Set Multiple Cells’ Values at Once
- Set Cell Value – Text
- Set Cell Value – Variable
- Get Cell Value
- VBA Coding Made Easy
- Get ActiveCell Value
- Assign Cell Value to Variable
- Other Cell Value Examples
- Copy Cell Value
- Compare Cell Values
- VBA Code Examples Add-in
- Get, Set, or Change Cell value in Excel VBA
- Set Cell Value
- Set the value to a single cell
- Get Cell Value
- Change Cell Values
VBA Ranges — Getting and Setting Cell Values
In the previous post, we introduced the VBA Range object. This gave us the foundation of working with Ranges in VBA. In today’s post, I’d like to discuss how to get and set cell values through VBA. This will continue to build up our understanding of the VBA Range object and how to use it. There are several ways you can get and set cell values with VBA and I’ll do my best to cover all the necessities, but at the same time keeping it short and to the point. Let’s get started.
Getting Cell Values
To get a cell’s value in VBA, we need to refer to it with the Range object and then call the .Value property.
We’ll use the following spreadsheet for our example. It’s a simple table with some names in it.
To get the value from cell A2 you can use this code snippet:
This will take cell A2 and put it in the variable val . Then we print out the value in the Immediate Window (which the value in our example is Joseph ).
You can also set the range to a variable and access the value from that variable as well:
What happens if you use .Value on a set of cells?
Let’s change our previous code snippet to the following:
If you run this code, you will get an error stating that there is a type mismatch.
What’s going on here?
The problem is that when you work with a set of cells, .Value can only return a single value. So when we ask VBA to return .Value on our variable (which refers to multiple cells), the .Value property doesn’t know which cell we are referring to.
How do you get a single cell from a set of cells?
In order to use .Value to get a value from a cell, we need to refer to a single cell from the range of cells in our variable. The way we do that is with the Cells() VBA function.
The Range.Cells Function
The Cells() function is a way to take a range of cells and return a single cell from the set. Here is the function defined:
Parameter | Type | Definition |
---|---|---|
row_number | Integer | The row number from within the range that you want to refer to. |
column_number | Integer | The column number from within the range that you want to refer to. |
Take a look at the following code:
Here we took the range of A2:A5 and referred to row 1 column 1. Since the range variable cellRange refers to A2:A5 , the first row is row 2 and the first column is A .
When using the Cells() function, remember that row 1 and column 1 represent the top-left most cell within the range that the Cells() function is working on. If your range is A1:D5 , then Cells(1, 1) will refer to A1 , but if your range is B2:D6 , then Cells(1, 1) refers to B2 .
Ok, that covers getting cell values from range objects, now let’s discuss setting cell values with range objects.
Does this article help you? If so, please consider supporting me with a coffee в•пёЏ
Setting Cell Values
In order to set a cell’s value, you can use the same .Value property when referring to a cell. In this example, we’ll take A2 ’s value and change it from Joseph to John :
First we set the variable cellRange to A2 . Then we said cellRange.Value = «John» which changes the variable’s .Value property. Remember, though, that the variable is a reference to cell A2 , so whatever you do to that variable, you also do to cell A2 in the worksheet. Finally, we output the value of A2 into the Immediate Window to see that it changed.
We can also see the value changed in the worksheet after we run this code:
How do you set multiple cells’ values?
Remember how I said that you can only read from one cell using .Value ? Well, when setting values, you can actually set multiple cells at one time by using .Value . Take a look at the following code:
If you ran this code, it would set all A2:A5 ’s cells to John :
Well, maybe you’d actually want to do this for some other scenarios, like when you want a bunch of cells to repeat a value.
Let’s take a real example for a second. Let’s say we have two columns, First Name and Last Name . We want to take the Last Name column and place its value after the First Name ’s value; essentially combining the values to make a single Name column.
Here’s our sample data:
Our task is to combine the first and last name columns and place the result in column A . How do we do that?
One solution is to loop through cells A2 through A5 and then set that cell’s value to its own value, plus a space, plus the last name of the cell right next to it.
Sounds easy enough, let’s code it up:
Let’s step through the code.
- First, we create a variable called names . Then, we set that to range A2:A5 .
- Next, we create a variable called cell . This is going to be a temporary variable that will change with each iteration of the loop.
Then, we create the loop. Here, we’re looping through the names range object and setting the current item to the cell variable. This means that each time we run through the loop, cell represents a single range object.
*The first time the loop is run, cell is set to A2 . Then, A3 , next A4 , and finally A5 . After that, there are no more cells to go through in the names variable, so the loop ends.
- I’ll go over how to loop through ranges in a future post since this post is already long enough!
Now we’re ready to combine the first and last names. How we do that is with another Range function called Offset(_rows_, _columns_) . The idea with this function is that if you’re on a cell like A2 and you say cell.Offset(0, 1) what we’re really saying is “move over one column to the right”. This puts us on cell B2 . That’s how we’re able to get the last name in our example.
- I’ll discuss how to use the Offset() function in more detail in a future post. Again, this post has gone on long enough.
Here are the results of the code after we run it:
From here, we could change the A1 cell to just Name and delete column B altogether.
Getting and Setting Cell Values from a Named Range or Table Name
One last thing I’d like to touch on is when you use the Range() function, you can use a named range or table name instead of a range like A2:A5 . In our first example, our data is in a table named Table1 . To refer to the data of the table, we could use the following:
And to refer to the entire table, we can leverage structured referencesВ like so:
This will return A1 ’s value “Name” since the table starts in A1 .
Also, if you’re new to Excel Tables, click here to learn more.
What’s next?
Honestly, there is so much to discuss with range objects in VBA. I’ll be touching on many more topics regarding ranges in VBA in upcoming posts such as:
- Modifying cell colors
- Finding cells by their text values
- Filtering data
- Getting the last row in a range (you need this more often than you think)
I’ll come back to this post and put links to these posts as I create them.
If you enjoyed this content, please share and subscribe!
Wow, you read the whole article! You know, people who make it this far are true learners. And clearly, you value learning. Would you like to learn more about Excel? Please consider supporting me by buying me a coffee (it takes a lot of coffee to write these articles!).
Written by Joseph who loves teaching about Excel.
Источник
VBA Cell Value – Get, Set, or Change
In this Article
This tutorial will teach you how to interact with Cell Values using VBA.
Set Cell Value
To set a Cell Value, use the Value property of the Range or Cells object.
Range.Value & Cells.Value
There are two ways to reference cell(s) in VBA:
- Range Object – Range(“A2”).Value
- Cells Object – Cells(2,1).Value
The Range object allows you to reference a cell using the standard “A1” notation.
This will set the range A2’s value = 1:
The Cells object allows you to reference a cell by it’s row number and column number.
This will set range A2’s value = 1:
Notice that you enter the row number first:
Set Multiple Cells’ Values at Once
Instead of referencing a single cell, you can reference a range of cells and change all of the cell values at once:
Set Cell Value – Text
In the above examples, we set the cell value equal to a number (1). Instead, you can set the cell value equal to a string of text. In VBA, all text must be surrounded by quotations:
If you don’t surround the text with quotations, VBA will think you referencing a variable…
Set Cell Value – Variable
You can also set a cell value equal to a variable
Get Cell Value
You can get cell values using the same Value property that we used above.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Get ActiveCell Value
To get the ActiveCell value and display it in a message box:
Assign Cell Value to Variable
To get a cell value and assign it to a variable:
Here we used a variable of type Variant. Variant variables can accept any type of values. Instead, you could use a String variable type:
A String variable type will accept numerical values, but it will store the numbers as text.
If you know your cell value will be numerical, you could use a Double variable type (Double variables can store decimal values):
However, if you attempt to store a cell value containing text in a double variable, you will receive an type mismatch error:
Other Cell Value Examples
Copy Cell Value
It’s easy to set a cell value equal to another cell value (or “Copy” a cell value):
You can even do this with ranges of cells (the ranges must be the same size):
Compare Cell Values
You can compare cell values using the standard comparison operators.
Test if cell values are equal:
Will return TRUE if cell values are equal. Otherwise FALSE.
You can also create an If Statement to compare cell values:
You can compare text in the same way (Remember that VBA is Case Sensitive)
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Get, Set, or Change Cell value in Excel VBA
We use VBA to automate our tasks in excel. The idea of using VBA is to connect the interface of excel with the programming. One of the very most connections between them is by changing the cell values. The change in cell value by programming shows the power of VBA. In this article, we will see how to set, get and change the cell value.
Set Cell Value
Assigning a cell with a value can be achieved by very two famous functions in VBA i.e. Range and Cells function.
Range Function in VBA
The range function helps access the cells in the worksheet. To set the cell value using the range function, we use the .Value.
Syntax: Range(cell_name).Value = value_to_be_assinged.
Set the value to a single cell
If you want to assign ’11’ to cell A1, then the following are the steps:
Step 1: Use the Range function, in the double quotes type the cell name. Use .Value object function. For example, Range(“A1”).Value = 11.
Step 2: Run your macro. The number 11 appears in cell A1.
Set the value to multiple cells at the same time
Remember the days, when your teacher gives you punishment, by making you write the homework 10 times, those were the hard days, but now the effort has exponentially reduced. You can set a value to a range of cells with just one line of code. If you want to write your name, for example, “Arushi” 10 times, in the range A2 to A11. Use range function. Following are the steps:
Step 1: Use the Range function, in the double quotes, write “Start_of_cell: End_of_cell”. Use .Value object function. For example, Range(“A2:A11”).Value = “Arushi”.
Step 2: Run your macro. The text “Arushi” appears from cell A2 to A11 inclusive.
Cells Function in VBA
The Cells function is similar to the range function and is also used to set the cell value in a worksheet by VBA. The difference lies in the fact that the Cells function can only set a single cell value at a time while the Range function can set multiple values at a time. Cells function use matrix coordinate system to access cell elements. For example, A1 can be written as (1, 1), B1 can be written as (1, 2), etc.
Syntax: Cells(row_number, column_number).Value = value_to_be_assign
For example, you want to set the cell value to “Arushi cleared CA with Rank “, in cell B1. Also, set cell C1, to ‘1’. Following are the steps:
Step 1: Open your VBA editor. Use cells function, as we want to access cell B1, the matrix coordinates will be (1, 2). Type, Cells(1, 2).Value = “Arushi cleared CA with Rank” in the VBA code.
Step 2: To access cell C1, the matrix coordinates are (1, 3). Type, Cells(1, 3).Value = 1 in the VBA code.
Step 3: Run your macro. The required text appears in cell B1, and a number appears in C1.
Setting Cell values by Active cell and the input box
There are other ways by which you can input your value in the cell in a worksheet.
Active Cell
You can set the cell value of a cell that is currently active. An active cell is the selected cell in which data is entered if you start typing. Use ActiveCell.Value object function to set the value either to text or to a number.
Syntax: ActiveCell.Value = value_to_be_assigned
For example, you want to assign the active cell with a text i.e. “Arushi is practicing CA”, also want to change the color of the cell to yellow. Following are the steps:
Step 1: Use the ActiveCell object to access the currently selected cell in the worksheet. Use ActiveCell.Value function object to write the required text.
Step 2: Color the cell by using ActiveCell.Interior.Color function. For example, use vbYellow to set your cell color to yellow.
Step 3: Run your macro. The currently selected cell i.e. B1 has attained the requirements.
Input Box
You can use the input box to set the cell value in a worksheet. The input box takes the custom value and stores the result. This result could further be used to set the value of the cell. For example, set the cell value of A1, dynamically by taking input, from the input box.
Following are the steps
Step 1: Open your VBA editor. A sub-procedure name geeks() is created. Use the Range function to store the value given by the input box.
Step 2: Run your Macro. A dialogue-box name Microsoft Excel appears. Enter the value to be stored. For example, “geeks for geeks”. Click Ok.
Step 3: Open your worksheet. In cell A1, you will find the required text is written.
Get Cell Value
After setting the cell value, it’s very important to have a handsome knowledge of how to display the cell value. There can be two ways two get the cell value either print the value in the console or create a message box.
Print Cell Value in Console
The console of the VBA editor is the immediate window. The immediate window prints the desired result in the VBA editor itself. The cell value can be stored in a variable and then printed in the immediate window. For example, you are given a cell A1 with the value ’11’, and you need to print this value in the immediate window.
Following are the steps
Step 1: Press Ctrl + G to open the immediate window.
Step 2: The cell value in A1 is 1.
Step 3: Open your VBA editor. Declare a variable that could store the cell value. For example, Val is the variable that stores the cell value in A1. Use the Range function to access the cell value. After storing the cell value in the val, print the variable in the immediate window with the help of Debug.Print(val) function.
Step 4: Run your macro. The cell value in A1 is printed in the immediate window.
Print Cell Value in a Message Box
A message box can also be used to show the cell value in VBA. For example, a random string is given in cell A1 of your string i.e. “Arushi studies in Hansraj”. Now, if you want to display the cell value in A1, we can use Message Box to achieve this.
Following are the steps
Step 1: Open your VBA macro. Create a message box by using MsgBox. Use the Range(cell).Value function to access the cell value.
Step 2: Run your macro. A message box appears, which contains the cell value of A1.
Change Cell Values
The value, once assigned to the cell value, can be changed. Cell values are like variables whose values can be changed any number of times. Either you can simply reassign the cell value or you can use different comparators to change the cell value according to a condition.
By reassigning the Cell Value
You can change the cell value by reassigning it. In the below example, the value of cell A1 is initially set to 1, but later it is reassigned to 2.
Following are the steps
Step 1: Open your VBA code editor. Initially, the value of cell A1 is assigned to 1. This initial value is printed in the immediate window. After that, we changed the value of cell A1 to 2. Now, if we print the A1 value in the immediate window, it comes out to be 2.
Step 2: The immediate window shows the output as 1 and 2.
Changing cell value with some condition
We can use if-else or switch-case statements to change the cell value with some condition. For example, if your age is greater than 18 then you can drive else you cannot drive. You can output your message according to this condition.
Following are the steps
Step 1: A code is written in the image below, which tells whether you are eligible for a driving license or not. If your age is greater than 18 then cell A1 will be assigned with the value, “You are eligible for the driving license”, else A1 will be assigned with “You are not eligible for driving license”.
Step 2: Run your macro. An input box appears. Enter your age. For example, 19.
Step 3: According to the age added the cell value will be assigned.
Источник
In this VBA Tutorial, you learn how to set a cell’s or cell range’s value and get a cell’s or cell range’s value.
This VBA Tutorial is accompanied by Excel workbooks containing the macros and data I use in the examples below. You can get immediate access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section that interests you.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Begin working with macros here.
- Learn about basic VBA constructs and structures here.
- Learn how to enable or disable macros in Excel here.
- Learn how to work with the Visual Basic Editor here.
- Learn how to work with Sub procedures here.
- Learn how to create object references here.
- Learn several ways to refer to cell ranges here.
- Learn how to work with properties here.
- Learn how to declare and assign data to variables here.
- Learn about VBA data types here.
- Learn how to work with arrays here.
- Learn how to work with R1C1-style references here.
- Learn how to work with loops here.
- Practical VBA applications and macro examples:
- Learn how to copy and paste values here.
- Learn how to find the last row in a worksheet here.
- Learn how to find the last column in a worksheet here.
- Learn how to specify a column’s width here.
- Learn how to convert strings to numbers here.
You can find additional VBA and Macro Tutorials in the Archives.
#1: Set cell value
VBA code to set cell value
To set a cell’s value with VBA, use a statement with the following structure:
Cell.ValueOrValue2 = CellValue
Process to set cell value
To set a cell’s value with VBA, follow these steps:
- Identify and return a Range object representing the cell whose value you want to set (Cell).
- Set the cell’s value with the Range.Value or Range.Value2 property (ValueOrValue2 = CellValue).
VBA statement explanation
- Item: Cell.
- VBA construct: Range object.
- Description: Cell is a Range object representing the cell whose value you want to set.
For purposes of returning such a Range object, work with constructs such as the Worksheet.Range, Worksheet.Cells, Application.ActiveCell, Application.Selection, Range.Range, Range.Cells, or Range.Offset properties.
If you explicitly declare an object variable to represent Cell, use the Range object data type.
- Item: Value or Value2.
- VBA construct: Range.Value or Range.Value2 property.
- Description: Both the Range.Value and Range.Value2 properties set the value of Cell.
The difference between Range.Value and Range.Value2 is the data types they work with. Range.Value2 doesn’t use Currency nor Date. This difference is particularly important for purposes of getting a cell’s value. For a more detailed discussion of this topic, please refer to the appropriate section.
- Item: =.
- VBA construct: Assignment operator.
- Description: The = operator assigns the value returned by the expression on its right (CellValue) to the property on its left (Cell.ValueOrValue2).
- Item: CellValue.
- VBA construct: New value of Range.Value or Range.Value2 property.
- Description: CellValue is the new value you specify for Cell. You can specify, among others, numeric values or text strings.
Macro examples to set cell value
The following macro example sets a cell’s (myCellSetValue) value to the string “set cell value with Range.Value” with the Range.Value property.
Sub setCellValue() 'source: https://powerspreadsheets.com/ 'sets a cell's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare object variable to hold reference to cell where you write the value Dim myCellSetValue As Range 'identify cell where you set the value Set myCellSetValue = ThisWorkbook.Worksheets("set cell value").Range("A7") 'set cell value with Range.Value property myCellSetValue.Value = "set cell value with Range.Value" End Sub
The following macro example sets a cell’s (myCellSetValue2) value to the string “set cell value with Range.Value2” with the Range.Value2 property.
Sub setCellValue2() 'source: https://powerspreadsheets.com/ 'sets a cell's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare object variable to hold reference to cell where you write the value Dim myCellSetValue2 As Range 'identify cell where you set the value Set myCellSetValue2 = ThisWorkbook.Worksheets("set cell value").Range("A11") 'set cell value with Range.Value2 property myCellSetValue2.Value2 = "set cell value with Range.Value2" End Sub
Effects of executing macro example to set cell value
The following GIF illustrates the results of executing the first macro example, which works with the Range.Value property. The value of cell A7 is set to the string “set cell value with Range.Value”.
The following GIF illustrates the results of executing the second macro example, which works with the Range.Value2 property. The value of cell A11 is set to the string “set cell value with Range.Value2”.
#2: Set cell range value
VBA code to set cell range value
To set a cell range’s value with VBA, use a statement with the following structure:
CellRange.ValueOrValue2 = CellRangeValue
Process to set cell range value
To set a cell range’s value with VBA, follow these steps:
- Identify and return a Range object representing the cell range whose value you want to set (CellRange).
- Set the cell range’s value with the Range.Value or Range.Value2 property (ValueOrValue2 = CellRangeValue).
VBA statement explanation
- Item: CellRange.
- VBA construct: Range object.
- Description: CellRange is a Range object representing the cell range whose value you want to set.
For purposes of returning such a Range object, work with constructs such as the Worksheet.Range, Worksheet.Cells, Application.Selection, Range.Range, Range.Cells, Range.Offset or Range.Resize properties.
If you explicitly declare an object variable to represent CellRange, use the Range object data type.
- Item: ValueOrValue2.
- VBA construct: Range.Value or Range.Value2 property.
- Description: Both the Range.Value and Range.Value2 properties set the value of CellRange.
The difference between Range.Value and Range.Value2 is the data types they work with. Range.Value2 doesn’t use Currency nor Date. This difference is particularly important for purposes of getting a cell range’s value. For a more detailed discussion of this topic, please refer to the appropriate section.
- Item: =.
- VBA construct: Assignment operator.
- Description: The = operator assigns the value returned by the expression on its right (CellRangeValue) to the property on its left (CellRange.ValueOrValue2).
- Item: CellRangeValue.
- VBA construct: New value of Range.Value or Range.Value2 property.
- Description: CellRangeValue is the new value you specify for CellRange. You can specify, among others, numeric values or text strings.
Macro examples to set cell range value
The following macro example sets a cell range’s (myCellRangeSetValue) value to the string “set cell range value with Range.Value” with the Range.Value property.
Sub setCellRangeValue() 'source: https://powerspreadsheets.com/ 'sets a cell range's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare object variable to hold reference to cell range where you write the value Dim myCellRangeSetValue As Range 'identify cell range where you set the value Set myCellRangeSetValue = ThisWorkbook.Worksheets("set cell value").Range("A15:C19") 'set cell range value with Range.Value property myCellRangeSetValue.Value = "set cell range value with Range.Value" End Sub
The following macro example sets a cell range’s (myCellRangeSetValue2) value to the string “set cell range value with Range.Value2” with the Range.Value2 property.
Sub setCellRangeValue2() 'source: https://powerspreadsheets.com/ 'sets a cell range's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare object variable to hold reference to cell range where you write the value Dim myCellRangeSetValue2 As Range 'identify cell range where you set the value Set myCellRangeSetValue2 = ThisWorkbook.Worksheets("set cell value").Range("A23:C27") 'set cell range value with Range.Value2 property myCellRangeSetValue2.Value = "set cell range value with Range.Value2" End Sub
Effects of executing macro example to set cell range value
The following GIF illustrates the results of executing the first macro example, which works with the Range.Value property. The value of cells A15 to C19 is set to the string “set cell range value with Range.Value”.
The following GIF illustrates the results of executing the second macro example, which works with the Range.Value2 property. The value of cells A23 to C27 is set to the string “set cell range value with Range.Value2”.
#3: Get cell value
VBA code to get cell value
To get a cell’s value with VBA, use a statement with the following structure:
myVariable = Cell.ValueOrValue2
Process to get cell value
To get a cell’s value with VBA, follow these steps:
- Identify and return a Range object representing the cell whose value you want to get (Cell).
- Get the cell’s value with the Range.Value or Range.Value2 property (ValueOrValue2).
- Assign the value returned by Range.Value or Range.Value to a variable (myVariable =).
VBA statement explanation
- Item: myVariable.
- VBA construct: Variable.
- Description: myVariable is the variable you want to hold Cell’s value.
If you explicitly declare myVariable, use a data type that’s capable of holding all the potential values that Cell may hold.
- Item: =.
- VBA construct: Assignment operator.
- Description: The = operator assigns the value returned by the expression on its right (Cell.ValueOrValue2) to the variable on its left (myVariable).
- Item: Cell.
- VBA construct: Range object.
- Description: Cell is a Range object representing the cell whose value you want to get.
For purposes of returning such a Range object, work with constructs such as the Worksheet.Range, Worksheet.Cells, Application.ActiveCell, Application.Selection, Range.Range, Range.Cells, or Range.Offset properties.
If you explicitly declare an object variable to represent Cell, use the Range object data type.
- Item: ValueOrValue2.
- VBA construct: Range.Value or Range.Value2 property.
- Description: Both the Range.Value and Range.Value2 properties return the value of Cell.
The difference between Range.Value and Range.Value2 is the data types they work with. Range.Value2 doesn’t use Currency nor Date. Therefore, if Cell’s number format is Date or Currency, Range.Value converts Cell’s value to the Date or Currency data type, as appropriate. Range.Value2 doesn’t carry out this conversion and, therefore, Range.Value2 generally returns such value as of the Double data type.
The Currency data type stores numbers in an integer format scaled by 10,000. this results in a fixed-point number with 4 decimal digits. If Cell’s value contains more decimal places, Range.Value and Range.Value2 tend to return different values. Generally, if Cell’s value may contain more than 4 decimal places, Range.Value2 is more accurate.
Macro examples to get cell value
The following macro example:
- Gets a cell’s (A7) value with the Range.Value property.
- Assigns the cell’s value to a variable (myValue).
- Displays a message box with the value held by the variable.
Sub getCellValue() 'source: https://powerspreadsheets.com/ 'gets a cell's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare variable to hold cell value Dim myValue As Variant 'get cell value with Range.Value property and assign it to variable myValue = ThisWorkbook.Worksheets("get cell value").Range("A7").Value 'display cell value MsgBox myValue End Sub
The following macro example:
- Gets a cell’s (A7) value with the Range.Value2 property.
- Assigns the cell’s value to a variable (myValue2).
- Displays a message box with the value held by the variable.
Sub getCellValue2() 'source: https://powerspreadsheets.com/ 'gets a cell's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare variable to hold cell value Dim myValue2 As Variant 'get cell value with Range.Value2 property and assign it to variable myValue2 = ThisWorkbook.Worksheets("get cell value").Range("A7").Value2 'display cell value MsgBox myValue2 End Sub
Effects of executing macro example to get cell value
The following GIF illustrates the results of executing the first macro example, which works with the Range.Value property. The message box displays the value of cell A7.
Notice that cell A7 is formatted as currency. The Range.Value property converts the cell’s value to the Currency data type, which results in a fixed-point number with 4 decimal digits. Therefore, the message box displays a value with only 4 decimal places, instead of the 10 decimal places that the original value in cell A7 has.
The following GIF illustrates the results of executing the second macro example, which works with the Range.Value2 property. The message box displays the value of cell A7.
The Range.Value2 property doesn’t work with the Currency data type. Therefore, the message box displays all the (10) decimal places that the original value in cell A7 has.
#4: Get cell range value
VBA code to get cell range value
To get a cell range’s value with VBA, use a statement with the following structure:
Dim myArray() As Variant myArray = CellRange.ValueOrValue2
Process to get cell range value
To get a cell range’s value with VBA, follow these steps:
- Declare an array of the Variant data type (myArray).
- Identify and return a Range object representing the cell range whose value you want to get (CellRange).
- Get the cell range’s value with the Range.Value or Range.Value2 property.
- Assign the value returned by Range.Value or Range.Value to the previously-declared array (myArray =).
VBA statement explanation
Line #1: Dim myArray As Variant
- Item: Dim myArray() As Variant.
- VBA construct: Dim statement.
- Description: The Dim statement declares an array (myArray) as of the Variant data type.
myArray is the array you want to hold CellRange’s values.
Line #2: myArray = CellRange.ValueOrValue2
- Item: myArray.
- VBA construct: Array.
- Description: myArray is the array you want to hold CellRange’s values.
- Item: =.
- VBA construct: Assignment operator.
- Description: The = operator assigns the values returned by the expression on its right (CellRange.ValueOrValue2) to the array on its left (myArray).
- Item: CellRange.
- VBA construct: Range object.
- Description: CellRange is a Range object representing the cell range whose values you want to get.
For purposes of returning such a Range object, work with constructs such as the Worksheet.Range, Worksheet.Cells, Application.Selection, Range.Range, Range.Cells, Range.Offset or Range.Resize properties.
If you explicitly declare an object variable to represent CellRange, use the Range object data type.
- Item: ValueOrValue2.
- VBA construct: Range.Value or Range.Value2 property.
- Description: Both the Range.Value and Range.Value2 properties return the values in CellRange.
The difference between Range.Value and Range.Value2 is the data types they work with. Range.Value2 doesn’t use Currency nor Date. Therefore, if CellRange’s number format is Date or Currency, Range.Value converts the values in CellRange to the Date or Currency data type, as appropriate. Range.Value2 doesn’t carry out this conversion and, therefore, Range.Value2 generally returns such values as of the Double data type.
The Currency data type stores numbers in an integer format scaled by 10,000. this results in a fixed-point number with 4 decimal digits. If CellRange’s values contain more decimal places, Range.Value and Range.Value2 tend to return different values. Generally, if CellRange’s values may contain more than 4 decimal places, Range.Value2 is more accurate.
Macro examples to get cell range value
The following macro example:
- Gets a cell range’s (A11 to C15) values with the Range.Value property.
- Assigns the cell range’s values to an array (myValuesArray).
- Loops through each value in the array.
- Displays a message box with each value it loops through.
Sub getCellRangeValues() 'source: https://powerspreadsheets.com/ 'gets a cell range's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare Variant array to hold cell range values Dim myValuesArray() As Variant 'declare variables to hold loop counters used to iterate through the individual values in the cell range Dim rowCounter As Long Dim columnCounter As Long 'get cell range values with Range.Value property and assign them to array myValuesArray = ThisWorkbook.Worksheets("get cell value").Range("A11:C15").Value 'loop through each value in array, step #1: loop through each value in first array dimension (rows) For rowCounter = LBound(myValuesArray, 1) To UBound(myValuesArray, 1) 'loop through each value in array, step #2: loop through each value in second array dimension (columns) For columnCounter = LBound(myValuesArray, 2) To UBound(myValuesArray, 2) 'display value loop is currently iterating through MsgBox myValuesArray(rowCounter, columnCounter) Next columnCounter Next rowCounter End Sub
The following macro example:
- Gets a cell range’s (A11 to C15) values with the Range.Value2 property.
- Assigns the cell range’s values to an array (myValues2Array).
- Loops through each value in the array.
- Displays a message box with each value it loops through.
Sub getCellRangeValues2() 'source: https://powerspreadsheets.com/ 'gets a cell range's value 'for further information: https://powerspreadsheets.com/excel-vba-value-value2/ 'declare Variant array to hold cell range values Dim myValues2Array() As Variant 'declare variables to hold loop counters used to iterate through the individual values in the cell range Dim rowCounter As Long Dim columnCounter As Long 'get cell range values with Range.Value2 property and assign them to array myValues2Array = ThisWorkbook.Worksheets("get cell value").Range("A11:C15").Value2 'loop through each value in array, step #1: loop through each value in first array dimension (rows) For rowCounter = LBound(myValues2Array, 1) To UBound(myValues2Array, 1) 'loop through each value in array, step #2: loop through each value in second array dimension (columns) For columnCounter = LBound(myValues2Array, 2) To UBound(myValues2Array, 2) 'display value loop is currently iterating through MsgBox myValues2Array(rowCounter, columnCounter) Next columnCounter Next rowCounter End Sub
Effects of executing macro example to get cell range value
The following GIF illustrates the results of executing the first macro example, which works with the Range.Value property. The message boxes display the values of cell A11 to C15.
Notice that the cell range is formatted as currency. The Range.Value property converts the cell range’s values to the Currency data type, which results in fixed-point numbers with 4 decimal digits. Therefore, the message boxes display values with a maximum of 4 decimal places, instead of the 10 decimal places that the original values in the cell range have.
The following GIF illustrates the results of executing the second macro example, which works with the Range.Value2 property. The message boxes display the values of cell A11 to C15.
The Range.Value2 property doesn’t work with the Currency data type. Therefore, the message boxes display all the (10) decimal places that the original values in the cell range have.
References to VBA Constructs Used in this VBA Tutorial
Use the following links to visit the appropriate webpage in the Microsoft Developer Network:
- Identify the cell or cell range whose value you want to set or get:
- Workbook object.
- Application.ThisWorkbook property.
- Application.ActiveWorkbook property.
- Application.Workbooks property.
- Worksheet object.
- Application.ActiveSheet property.
- Workbook.Worksheets property.
- Range object.
- Worksheet.Range property.
- Worksheet.Cells property.
- Application.ActiveCell property.
- Application.Selection property.
- Range.Range property.
- Range.Cells property.
- Range.Item property.
- Range.Offset property.
- Range.Resize property.
- Set or get the value of a cell or cell range:
- Range.Value property.
- Range.Value2 property.
- Work with variables, arrays and data types:
- Dim statement.
- Set statement.
- = operator.
- Loop through all the elements in an array:
- For… Next statement.
- LBound function.
- UBound function.
- Data types:
- Currency data type.
- Date data type.
- Double data type.
- Long data type.
- Variant data type.
- Display a message box:
- MsgBox function.