Setting a cell value in excel vba

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!

automacro

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:

get cell value assign variable

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

    Applying-range-function

    Step 2: Run your macro. The number 11 appears in cell A1

    Running-macro

    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”

    Applying-range-function

    Step 2: Run your macro. The text “Arushi” appears from cell A2 to A11 inclusive. 

    Running-macro

    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. 

    Using-cell-functions

    Step 2: To access cell C1, the matrix coordinates are (1, 3). Type, Cells(1, 3).Value = 1 in the VBA code. 

    Accessing-cell-C1

    Step 3: Run your macro. The required text appears in cell B1, and a number appears in C1. 

    Running-macro

    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. 

    Using-active-cell-function

    Step 2: Color the cell by using ActiveCell.Interior.Color function. For example, use vbYellow to set your cell color to yellow. 

    Using-active.cell.interior.color-function

    Step 3: Run your macro. The currently selected cell i.e. B1 has attained the requirements. 

    Running-macro

    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. 

    Using-range-function

    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

    Entering-value-to-be-stored

    Step 3: Open your worksheet. In cell A1, you will find the required text is written. 

    Text-written-in-A1

    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. 

    Opening-immediate-window

    Step 2: The cell value in A1 is 1

    Value-in-A1

    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.

    Printing-variable-in-immediate-window

    Step 4: Run your macro. The cell value in A1 is printed in the immediate window. 

    Running-macro

    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. 

    Text-present-in-A1

    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. 

    Creating-a-message-box

    Step 2: Run your macro. A message box appears, which contains the cell value of A1

    Running-macro

    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

    Changing-value-in-cell

    Step 2: The immediate window shows the output as 1 and 2. 

    Immediate-window-shows-output

    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”. 

    Text-assigned-to-A1

    Step 2: Run your macro. An input box appears. Enter your age. For example, 19. 

    Running-macro

    Step 3: According to the age added the cell value will be assigned. 

    Cell-value-assigned

    Excel VBA Tutorial about how to set or get a cell or cell range value with macrosIn 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:

    1. Identify and return a Range object representing the cell whose value you want to set (Cell).
    2. Set the cell’s value with the Range.Value or Range.Value2 property (ValueOrValue2 = CellValue).

    VBA statement explanation

    1. 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.

    2. 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.

    3. 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).
    4. 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”.

    Macro sets 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”.

    Macro sets 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:

    1. Identify and return a Range object representing the cell range whose value you want to set (CellRange).
    2. Set the cell range’s value with the Range.Value or Range.Value2 property (ValueOrValue2 = CellRangeValue).

    VBA statement explanation

    1. 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.

    2. 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.

    3. 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).
    4. 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”.

    Macro sets 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”.

    Macro sets 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:

    1. Identify and return a Range object representing the cell whose value you want to get (Cell).
    2. Get the cell’s value with the Range.Value or Range.Value2 property (ValueOrValue2).
    3. Assign the value returned by Range.Value or Range.Value to a variable (myVariable =).

    VBA statement explanation

    1. 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.

    2. 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).
    3. 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.

    4. 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:

    1. Gets a cell’s (A7) value with the Range.Value property.
    2. Assigns the cell’s value to a variable (myValue).
    3. 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:

    1. Gets a cell’s (A7) value with the Range.Value2 property.
    2. Assigns the cell’s value to a variable (myValue2).
    3. 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.

    Macro gets 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 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.

    Macro gets cell value with Range.Value2

    #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:

    1. Declare an array of the Variant data type (myArray).
    2. Identify and return a Range object representing the cell range whose value you want to get (CellRange).
    3. Get the cell range’s value with the Range.Value or Range.Value2 property.
    4. 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

    1. 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

    1. Item: myArray.
      • VBA construct: Array.
      • Description: myArray is the array you want to hold CellRange’s values.
    2. 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).
    3. 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.

    4. 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:

    1. Gets a cell range’s (A11 to C15) values with the Range.Value property.
    2. Assigns the cell range’s values to an array (myValuesArray).
    3. Loops through each value in the array.
    4. 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:

    1. Gets a cell range’s (A11 to C15) values with the Range.Value2 property.
    2. Assigns the cell range’s values to an array (myValues2Array).
    3. Loops through each value in the array.
    4. 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.

    Macro gets cell range values with Range.Value

    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.

    Macro gets cell range values with Range.Value2

    References to VBA Constructs Used in this VBA Tutorial

    Use the following links to visit the appropriate webpage in the Microsoft Developer Network:

    1. 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.
    2. Set or get the value of a cell or cell range:
      • Range.Value property.
      • Range.Value2 property.
    3. 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.
    4. Display a message box:
      • MsgBox function.

    Свойства ячейки, часто используемые в коде VBA Excel. Демонстрация свойств ячейки, как структурной единицы объекта Range, на простых примерах.

    Объект Range в VBA Excel представляет диапазон ячеек. Он (объект Range) может описывать любой диапазон, начиная от одной ячейки и заканчивая сразу всеми ячейками рабочего листа.

    Примеры диапазонов:

    • Одна ячейка – Range("A1").
    • Девять ячеек – Range("A1:С3").
    • Весь рабочий лист в Excel 2016 – Range("1:1048576").

    Для справки: выражение Range("1:1048576") описывает диапазон с 1 по 1048576 строку, где число 1048576 – это номер последней строки на рабочем листе Excel 2016.

    В VBA Excel есть свойство Cells объекта Range, которое позволяет обратиться к одной ячейке в указанном диапазоне (возвращает объект Range в виде одной ячейки). Если в коде используется свойство Cells без указания диапазона, значит оно относится ко всему диапазону активного рабочего листа.

    Примеры обращения к одной ячейке:

    • Cells(1000), где 1000 – порядковый номер ячейки на рабочем листе, возвращает ячейку «ALL1».
    • Cells(50, 20), где 50 – номер строки рабочего листа, а 20 – номер столбца, возвращает ячейку «T50».
    • Range("A1:C3").Cells(6), где «A1:C3» – заданный диапазон, а 6 – порядковый номер ячейки в этом диапазоне, возвращает ячейку «C2».

    Для справки: порядковый номер ячейки в диапазоне считается построчно слева направо с перемещением к следующей строке сверху вниз.

    Подробнее о том, как обратиться к ячейке, смотрите в статье: Ячейки (обращение, запись, чтение, очистка).

    В этой статье мы рассмотрим свойства объекта Range, применимые, в том числе, к диапазону, состоящему из одной ячейки.

    Еще надо добавить, что свойства и методы объектов отделяются от объектов точкой, как в третьем примере обращения к одной ячейке: Range("A1:C3").Cells(6).

    Свойства ячейки (объекта Range)

    Свойство Описание
    Address Возвращает адрес ячейки (диапазона).
    Borders Возвращает коллекцию Borders, представляющую границы ячейки (диапазона). Подробнее…
    Cells Возвращает объект Range, представляющий коллекцию всех ячеек заданного диапазона. Указав номер строки и номер столбца или порядковый номер ячейки в диапазоне, мы получаем конкретную ячейку. Подробнее…
    Characters Возвращает подстроку в размере указанного количества символов из текста, содержащегося в ячейке. Подробнее…
    Column Возвращает номер столбца ячейки (первого столбца диапазона). Подробнее…
    ColumnWidth Возвращает или задает ширину ячейки в пунктах (ширину всех столбцов в указанном диапазоне).
    Comment Возвращает комментарий, связанный с ячейкой (с левой верхней ячейкой диапазона).
    CurrentRegion Возвращает прямоугольный диапазон, ограниченный пустыми строками и столбцами. Очень полезное свойство для возвращения рабочей таблицы, а также определения номера последней заполненной строки.
    EntireColumn Возвращает весь столбец (столбцы), в котором содержится ячейка (диапазон). Диапазон может содержаться и в одном столбце, например, Range("A1:A20").
    EntireRow Возвращает всю строку (строки), в которой содержится ячейка (диапазон). Диапазон может содержаться и в одной строке, например, Range("A2:H2").
    Font Возвращает объект Font, представляющий шрифт указанного объекта. Подробнее о цвете шрифта…
    HorizontalAlignment Возвращает или задает значение горизонтального выравнивания содержимого ячейки (диапазона). Подробнее…
    Interior Возвращает объект Interior, представляющий внутреннюю область ячейки (диапазона). Применяется, главным образом, для возвращения или назначения цвета заливки (фона) ячейки (диапазона). Подробнее…
    Name Возвращает или задает имя ячейки (диапазона).
    NumberFormat Возвращает или задает код числового формата для ячейки (диапазона). Примеры кодов числовых форматов можно посмотреть, открыв для любой ячейки на рабочем листе Excel диалоговое окно «Формат ячеек», на вкладке «(все форматы)». Свойство NumberFormat диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковый числовой формат. Если нужно присвоить ячейке текстовый формат, записывается так: Range("A1").NumberFormat = "@". Общий формат: Range("A1").NumberFormat = "General".
    Offset Возвращает объект Range, смещенный относительно первоначального диапазона на указанное количество строк и столбцов. Подробнее…
    Resize Изменяет размер первоначального диапазона до указанного количества строк и столбцов. Строки добавляются или удаляются снизу, столбцы – справа. Подробнее…
    Row Возвращает номер строки ячейки (первой строки диапазона). Подробнее…
    RowHeight Возвращает или задает высоту ячейки в пунктах (высоту всех строк в указанном диапазоне).
    Text Возвращает форматированный текст, содержащийся в ячейке. Свойство Text диапазона возвращает значение NULL, за исключением тех случаев, когда все ячейки в диапазоне имеют одинаковое содержимое и один формат. Предназначено только для чтения. Подробнее…
    Value Возвращает или задает значение ячейки, в том числе с отображением значений в формате Currency и Date. Тип данных Variant. Value является свойством ячейки по умолчанию, поэтому в коде его можно не указывать.
    Value2 Возвращает или задает значение ячейки. Тип данных Variant. Значения в формате Currency и Date будут отображены в виде чисел с типом данных Double.
    VerticalAlignment Возвращает или задает значение вертикального выравнивания содержимого ячейки (диапазона). Подробнее…

    В таблице представлены не все свойства объекта Range. С полным списком вы можете ознакомиться не сайте разработчика.

    Простые примеры для начинающих

    Вы можете скопировать примеры кода VBA Excel в стандартный модуль и запустить их на выполнение. Как создать стандартный модуль и запустить процедуру на выполнение, смотрите в статье VBA Excel. Начинаем программировать с нуля.

    Учтите, что в одном программном модуле у всех процедур должны быть разные имена. Если вы уже копировали в модуль подпрограммы с именами Primer1, Primer2 и т.д., удалите их или создайте еще один стандартный модуль.

    Форматирование ячеек

    Заливка ячейки фоном, изменение высоты строки, запись в ячейки текста, автоподбор ширины столбца, выравнивание текста в ячейке и выделение его цветом, добавление границ к ячейкам, очистка содержимого и форматирования ячеек.

    Если вы запустите эту процедуру, информационное окно MsgBox будет прерывать выполнение программы и сообщать о том, что произойдет дальше, после его закрытия.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    Sub Primer1()

    MsgBox «Зальем ячейку A1 зеленым цветом и запишем в ячейку B1 текст: «Ячейка A1 зеленая!»»

    Range(«A1»).Interior.Color = vbGreen

    Range(«B1»).Value = «Ячейка A1 зеленая!»

    MsgBox «Сделаем высоту строки, в которой находится ячейка A2, в 2 раза больше высоты ячейки A1, « _

    & «а в ячейку B1 вставим текст: «Наша строка стала в 2 раза выше первой строки!»»

    Range(«A2»).RowHeight = Range(«A1»).RowHeight * 2

    Range(«B2»).Value = «Наша строка стала в 2 раза выше первой строки!»

    MsgBox «Запишем в ячейку A3 высоту 2 строки, а в ячейку B3 вставим текст: «Такова высота второй строки!»»

    Range(«A3»).Value = Range(«A2»).RowHeight

    Range(«B3»).Value = «Такова высота второй строки!»

    MsgBox «Применим к столбцу, в котором содержится ячейка B1, метод AutoFit для автоподбора ширины»

    Range(«B1»).EntireColumn.AutoFit

    MsgBox «Выделим текст в ячейке B2 красным цветом и выровним его по центру (по вертикали)»

    Range(«B2»).Font.Color = vbRed

    Range(«B2»).VerticalAlignment = xlCenter

    MsgBox «Добавим к ячейкам диапазона A1:B3 границы»

    Range(«A1:B3»).Borders.LineStyle = True

    MsgBox «Сделаем границы ячеек в диапазоне A1:B3 двойными»

    Range(«A1:B3»).Borders.LineStyle = xlDouble

    MsgBox «Очистим ячейки диапазона A1:B3 от заливки, выравнивания, границ и содержимого»

    Range(«A1:B3»).Clear

    MsgBox «Присвоим высоте второй строки высоту первой, а ширине второго столбца — ширину первого»

    Range(«A2»).RowHeight = Range(«A1»).RowHeight

    Range(«B1»).ColumnWidth = Range(«A1»).ColumnWidth

    MsgBox «Демонстрация форматирования ячеек закончена!»

    End Sub

    Вычисления в ячейках (свойство Value)

    Запись двух чисел в ячейки, вычисление их произведения, вставка в ячейку формулы, очистка ячеек.

    Обратите внимание, что разделителем дробной части у чисел в VBA Excel является точка, а не запятая.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    Sub Primer2()

    MsgBox «Запишем в ячейку A1 число 25.3, а в ячейку B1 — число 34.42»

    Range(«A1»).Value = 25.3

    Range(«B1»).Value = 34.42

    MsgBox «Запишем в ячейку C1 произведение чисел, содержащихся в ячейках A1 и B1»

    Range(«C1»).Value = Range(«A1»).Value * Range(«B1»).Value

    MsgBox «Запишем в ячейку D1 формулу, которая перемножает числа в ячейках A1 и B1»

    Range(«D1»).Value = «=A1*B1»

    MsgBox «Заменим содержимое ячеек A1 и B1 на числа 6.258 и 54.1, а также активируем ячейку D1»

    Range(«A1»).Value = 6.258

    Range(«B1»).Value = 54.1

    Range(«D1»).Activate

    MsgBox «Мы видим, что в ячейке D1 произведение изменилось, а в строке состояния отображается формула; « _

    & «следующим шагом очищаем задействованные ячейки»

    Range(«A1:D1»).Clear

    MsgBox «Демонстрация вычислений в ячейках завершена!»

    End Sub

    Так как свойство Value является свойством ячейки по умолчанию, его можно было нигде не указывать. Попробуйте удалить .Value из всех строк, где оно встречается и запустить код заново.

    Различие свойств Text, Value и Value2

    Построение с помощью кода VBA Excel таблицы с результатами сравнения того, как свойства Text, Value и Value2 возвращают число, дату и текст.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    Sub Primer3()

    ‘Присваиваем ячейкам всей таблицы общий формат на тот

    ‘случай, если формат отдельных ячеек ранее менялся

    Range(«A1:E4»).NumberFormat = «General»

    ‘добавляем сетку (границы ячеек)

    Range(«A1:E4»).Borders.LineStyle = True

    ‘Создаем строку заголовков

    Range(«A1») = «Значение»

    Range(«B1») = «Код формата» ‘формат соседней ячейки в столбце A

    Range(«C1») = «Свойство Text»

    Range(«D1») = «Свойство Value»

    Range(«E1») = «Свойство Value2»

    ‘Назначаем строке заголовков жирный шрифт

    Range(«A1:E1»).Font.Bold = True

    ‘Задаем форматы ячейкам A2, A3 и A4

    ‘Ячейка A2 — числовой формат с разделителем триад и двумя знаками после запятой

    ‘Ячейка A3 — формат даты «ДД.ММ.ГГГГ»

    ‘Ячейка A4 — текстовый формат

    Range(«A2»).NumberFormat = «# ##0.00»

    Range(«A3»).NumberFormat = «dd.mm.yyyy»

    Range(«A4»).NumberFormat = «@»

    ‘Заполняем ячейки A2, A3 и A4 значениями

    Range(«A2») = 2362.4568

    Range(«A3») = CDate(«01.01.2021»)

    ‘Функция CDate преобразует текстовый аргумент в формат даты

    Range(«A4») = «Озеро Байкал»

    ‘Заполняем ячейки B2, B3 и B4 кодами форматов соседних ячеек в столбце A

    Range(«B2») = Range(«A2»).NumberFormat

    Range(«B3») = Range(«A3»).NumberFormat

    Range(«B4») = Range(«A4»).NumberFormat

    ‘Присваиваем ячейкам C2-C4 значения свойств Text ячеек A2-A4

    Range(«C2») = Range(«A2»).Text

    Range(«C3») = Range(«A3»).Text

    Range(«C4») = Range(«A4»).Text

    ‘Присваиваем ячейкам D2-D4 значения свойств Value ячеек A2-A4

    Range(«D2») = Range(«A2»).Value

    Range(«D3») = Range(«A3»).Value

    Range(«D4») = Range(«A4»).Value

    ‘Присваиваем ячейкам E2-E4 значения свойств Value2 ячеек A2-A4

    Range(«E2») = Range(«A2»).Value2

    Range(«E3») = Range(«A3»).Value2

    Range(«E4») = Range(«A4»).Value2

    ‘Применяем к таблице автоподбор ширины столбцов

    Range(«A1:E4»).EntireColumn.AutoFit

    End Sub

    Результат работы кода:

    Сравнение свойств ячейки Text, Value и Value2

    В таблице наглядно видна разница между свойствами Text, Value и Value2 при применении их к ячейкам с отформатированным числом и датой. Свойство Text еще отличается от Value и Value2 тем, что оно предназначено только для чтения.


    Понравилась статья? Поделить с друзьями:
  • Set word createobject word application
  • Set width of a column in excel vba
  • Set vba excel что это
  • Set vba excel описание
  • Set vba excel rows