Visual basic excel value

Свойства ячейки, часто используемые в коде 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 тем, что оно предназначено только для чтения.


Value is a property in VBA mostly used with the range method to assign a value to a specific range. It is an inbuilt expression in VBA. For example, if we use range(“B3”).value = 3, this will assign cell B3 a value of 3, which does not necessarily mean that one must use the Value property with only the Range method. We can use it with other functions as well.

Early in our learning with VBA, we are curious to learn how to store the data in the cells. If you are that curious, you need to understand the “Value” property. This article will explain the “Value” property, insert or set values, get value from the cell, and many other things.

In one of the earlier articles, we discussed “VBA Range CellsRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.” The Range object can help us refer to single and multiple cells. To use the RANGE object first, we need to decide for which cell we need to insert the value and what value we will insert.

Table of contents
  • Excel VBA Value Property
    • How to use Value Property in VBA?
      • Example #1 – Range Object to Assign Values to Cells
      • Example #2 – Insert Value using CELLS Property
      • Example #3 – Get Cell Value
      • Example 4 – Error Value if More than One Cell Value Requires
    • Recommended Articles

VBA Value Property

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Value Property (wallstreetmojo.com)

How to use Value Property in VBA?

You can download this VBA Value Function Excel Template here – VBA Value Function Excel Template

Example #1 – Range Object to Assign Values to Cells

  • If you want to insert a value to cell A1, then you should refer the cell A1 like this Range(“A1”)

Code:

Sub Value()

  Range ("A1")

End Sub

VBA Value Example 1

  • After referring to the cell using the RANGE object, now put a dot (.) to see the IntelliSense list of all the properties and methods associated with this object.

Code:

Sub Value()

  Range ("A1").

End Sub

VBA Value Example 1-1

  • From this variety of options, select the property “VALUE.”

Code:

Sub Value()

  Range("A1").Value

End Sub

VBA Value Example 1-2

  • Once the VALUE property is selected, we need to set the value to cell A1 by putting the value in an equal sign.

Code:

Sub Value()

  Range("A1").Value = "Welcome to VBA"

End Sub

Example 1-3

  • It will insert the value “Welcome to VBA” to cell A1.

Example 1-4

  • If you want to insert the same value to multiple cells, refer to the cells like the code below.

Code:

Sub Value()

  Range("A1:A5").Value = "Welcome to VBA"

End Sub
  • It will insert the value from cell A1 to A5.

Example 1-5

  • If you want to insert values to different cells but not for the cell series, then we need to use code and the cell address in separate arguments like the one below.

Code:

Sub Value()

  Range("A1,A5,B4,C2").Value = "Welcome to VBA"

End Sub
  • It will insert the text “Welcome to VBA” to cells A1, A5, B4, and C2.

Example 1-6

Example #2 – Insert Value using CELLS Property

Not through the RANGE object but also using the VBA CELLS propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more, we can insert values. But, one of the problems with the CELLS object is we do not get access to the IntelliSense list as we got for the RANGE object.

Using CELLS Property

Here, we need to mention the row and column numbers. Then, we need to insert the value. For example, if you want to insert the value to cell A1, the code is CELLS(1,1). If you want to insert the value to the cell B5, then the code is CELLS(5,2), i.e., equal to the B5 cell.

We cannot insert values into multiple cells by using the CELLS property. This is unlike our RANGE object.

Example #3 – Get Cell Value

We have seen how to insert values into the cells. Now, we will see how to get values from cells.

Step 1: Define a variable as String.

Code:

Sub Value()

  Dim K As String

End Sub

Step 2: For this variable “k,” we will assign the value of the cell A1. In cell A1, we have entered the value “Welcome to VBA.”

Get Cell Value 1

So the code will be k = Range(“A1”).Value

Code:

Sub Value()

  Dim K As String

  K = Range("A1").Value

End Sub

Step 3: Show the variable “k” result in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub Value()

  Dim K As String

  K = Range("A1").Value

  MsgBox K

End Sub

By running the code, we should see the result of the cell A1 value in the message box.

Get Cell Value 1-2

We can also use the RANGE object to get the data of cell A1. The below code will show you the same.

Code:

Sub Value()

  Dim K As String

  Set CellValue = Range("A1")

  MsgBox CellValue

End Sub

It should also get the value of cell A1 in the message box.

Example 4 – Error Value if More than One Cell Value Requires

Look at the below code.

Code:

Sub Value()

  Dim K As Range

  Set CellValue = Range("A1:A5")

  MsgBox CellValue

End Sub

If you run the above code, we will get the “Type Mismatch” error.

We get this error when we set the object variable to more than one cell “value.” This is because the property does not understand which cell value is given, so it can get a single cell value at a time.

Recommended Articles

This article has been a guide to VBA Value Property. Here, we learn how to get the VBA object cell value and range to assign values to cells, along with examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA Union
  • VBA ArrayList
  • VBA UpperCase Function
  • Match in VBA

VBA Value

VBA Value

The journey of VBA starts with knowing how the values get stored in the cells. Therefore, knowing VALUE function under VBA is of more importance. After studying about VBA VALUE property, you will be able to know how the values get stored under VBA. This article explains all the types of VALUE function in VBA like how the value gets stored in cells, hot to set the value, how to insert the value and many more.

How to Use Excel VBA Value Function?

We will learn how to use VBA Value function with few examples in Excel.

You can download this VBA Value Excel Template here – VBA Value Excel Template

Example #1 – Set Cell Value using Range.Value function

Setting of cell/s value using Range. Value function roughly consists of two important steps:

  • Setting the range where you want the value to be stored.
  • Assigning a value to the range set.

Follow the below steps to set value in Excel VBA:

Step 1: Insert a new module under Visual Basic Editor (VBE).

vba value module

Step 2: Define a new sub-procedure under the inserted module so that a macro can be stored in it.

Code:

Sub VBA_Value_Ex1()

End Sub

vba value Example 1

Step 3: Define a new variable as a range which can be used to define a range where you wanted to store the value.

Code:

Sub VBA_Value_Ex1()

Dim setValue_Var As Range

End Sub

vba value Example 1.1

Step 4: With the help of the VBA RANGE function, assign the cells in the range to a variable defined with the help of the assignment operator.

Code:

Sub VBA_Value_Ex1()

Dim setValue_Var As Range
Set setValue_Var = ThisWorkbook.Worksheets("Setting_Cell_Value_1").Range("A1")

End Sub

vba value Example 1.2

Step 5: Now, use Range.Value property to be able to assign value to the range defined. Type the variable name “setValue_Var” under which the range is defined.

Sub VBA_Value_Ex1()

Dim setValue_Var As Range
Set setValue_Var = ThisWorkbook.Worksheets("Setting_Cell_Value_1").Range("A1")
setValue_Var

End Sub

vba value Example 1.3

Step 6: Put a dot (.) after variable to be able to select the IntelliSense list of functions available for this range variable defined.

Code:

Sub VBA_Value_Ex1()

Dim setValue_Var As Range
Set setValue_Var = ThisWorkbook.Worksheets("Setting_Cell_Value_1").Range("A1")
setValue_Var.

End Sub

vba value Example 1.4

Step 7: Drag down through the list and select “Value” function to store the value under this range variable.

Code:

Sub VBA_Value_Ex1()

Dim setValue_Var As Range
Set setValue_Var = ThisWorkbook.Worksheets("Setting_Cell_Value_1").Range("A1")
setValue_Var.Value

End Sub

vba value Example 1.5

Step 8: Assign “Welcome to the world of VBA!” as value to this range using assignment operator.

Code:

Sub VBA_Value_Ex1()

Dim setValue_Var As Range
Set setValue_Var = ThisWorkbook.Worksheets("Setting_Cell_Value_1").Range("A1")
setValue_Var.Value = "Welcome to the world of VBA!"

End Sub

vba value Example 1.6

Step 9: We are done with the coding part. Run this code by hitting F5 or Run button under VBE and see the output.

vba value 1

You also can assign the value to a range of cells. All you have to do is while setting the range for the output you will give one-dimensional array instead of a single cell reference.

Step 10: In the same code above, change the Range from “A1” to “A1: A5”.

Code:

Sub VBA_Value_Ex1()

Dim setValue_Var As Range
Set setValue_Var = ThisWorkbook.Worksheets("Setting_Cell_Value_1").Range("A1:A5")
setValue_Var.Value = "Welcome to the world of VBA!"

End Sub

vba value Example 1.7

Step 11: Hit F5 or Run button and see the output.

vba value Example 1.8

Example #2 – Set Cell Value using VBA Cells Property

This is another method for setting the cell value under VBA. Unlike the RANGE function, cells do not even need them. Value operator to be able to set value for the specific cell/s.

Follow the below steps to set the cell value in Excel VBA:

Step 1: Insert a new module under VBE where you can start writing your new piece of code.

New Module

Step 2: Add new sub-procedure under module inserted, where you can store your macro code in.

Code:

Sub VBA_Value_Ex2()

End Sub

vba example 2

Step 3: Start typing thisWorkbook.Worksheet to access the sheet named “Setting_Cell_Value_2”.

Code:

Sub VBA_Value_Ex2 ()

ThisWorkbook.worksheets

End Sub

vba example 2.2

Step 4: Mention the sheet name under parentheses in double quotes.

Code:

Sub VBA_Value_Ex2()

ThisWorkbook.Worksheets ("Setting_Cell_Value_2")

End Sub

vba example 2.1

Step 5: Use .Cells property to set the cell range from the given excel sheet.

Code:

Sub VBA_Value_Ex2()

ThisWorkbook.Worksheets("Setting_Cell_Value_2").Cells(1, 1)

End Sub

vba example 2.6

The first argument of the Cells property represents the rows and the second argument represents the column. Therefore, Cells(1, 1) means cell associated with the first row and first column of the sheet “Setting_Cell_Value_2”.

Step 6: Now, with the help of the assignment operator, assign a value to this cell set.

Code:

Sub VBA_Value_Ex2()

ThisWorkbook.Worksheets("Setting_Cell_Value_2").Cells(1, 1) = "VBA is Flexible."

End Sub

vba example 2.5

Have a look that we don’t need .Value function which we need to use while setting the value using Range function. Cells Method does not have such IntelliSense options.

Step 7: Hit F5 or Run button to run this code and see the output. You will see an output as shown in the screenshot below.

vba Value 2

Example #3 – Get Cell Value in VBA

Until now, in two examples we have seen how to set value for a cell or range of cells. Now suppose a case is exactly reverse, we have to get the value assigned to a particular cell of an excel sheet. How can we get that? Let’s go through a step by step guide.

Suppose I have assigned a value as shown in the screenshot below under the first cell of column A in sheet “Getting_Cell_Value”.

which programming language

Follow the below steps to get the cell value in Excel VBA:

Step 1: Insert a new module under VBE.

module long 3

Step 2: Add a sub-procedure so that a macro can be stored as a code.

Code:

Sub VBA_Value_Ex3()

End Sub

 Example 2.2

Step 3: Define a new variable called Get_Value as a Variant using VBA Dim function.

Code:

Sub VBA_Value_Ex3()

Dim Get_Value As Variant

End Sub

Example 2.3

Now, you have to assign the value present in cell A1 to the variable defined above.

Step 4: Type “Get_Value = ThisWorkbook.Worksheets”. This will allow the VBA compiler to access the excel sheet where your value is stored.

Code:

Sub VBA_Value_Ex3()

Dim Get_Value As Variant
Get_Value = ThisWorkbook.Worksheets

End Sub

Example 2.4

Step 5: Mention the worksheet name under parentheses with quotations in which value is stored.

Code:

Sub VBA_Value_Ex3()

Dim Get_Value As Variant
Get_Value = ThisWorkbook.Worksheets("Getting_Cell_Value")

End Sub

Example 2.5

Step 6: Now, use dot (.) Range method to provide the exact cell where value is stored under sheet named “Getting_Cell_Value”.

Code:

Sub VBA_Value_Ex3()

Dim Get_Value As Variant
Get_Value = ThisWorkbook.Worksheets("Getting_Cell_Value").Range("A1")

End Sub

Example 2.6

Step 7: Finally, use dot (.) Value method so that the actual value under cell A1 can be accessed by the compiler.

Code:

Sub VBA_Value_Ex3()

Dim Get_Value As Variant
Get_Value = ThisWorkbook.Worksheets("Getting_Cell_Value").Range("A1").Value

End Sub

Example 2.7

Step 8: As we have talked about, we need to get the value stored in cell A1. For that, use MsgBox to show the value of variable Get_Value (Which already have accessed the value typed in cell A1).

Code:

Sub VBA_Value_Ex3()

Dim Get_Value As Variant
Get_Value = ThisWorkbook.Worksheets("Getting_Cell_Value").Range("A1").Value
MsgBox Get_Value

End Sub

vba value Example 2.8

Step 9: Hit F5 or Run button to run this code, you will get the value present in cell A1 under the message box.

vba value 3 example

See, this was the value we have mentioned under cell A1 of sheet “Getting_Cell_Value”. Right?

Example #4 – Can we get Multiple Cell Values at a Time?

Let’s assume I have values stored in three different cells A1, A2, A3 as shown in the screenshot below:

vba value Example 3.1

Just don’t get confused if you see the text spread along columns A to E. it is just a visible layout (because I have merged the cells ) and the actual value is stored under cell A1, A2, A3 only.

Follow the below steps to use Excel VBA Value:

Step 1: Define a variable as a variant under a new sub-procedure in your VBA module.

Code:

Sub VBA_Value_Ex4()

Dim Get_Value_2 As Variant

End Sub

Add Variant

Step 2: Use Range.Value method to retrieve the value of cells A1: A3 and assign to a new variable defined in the previous step.

Code:

Sub VBA_Value_Ex4()

Dim Get_Value_2 As Variant
Get_Value_2 = ThisWorkbook.Worksheets("Getting_Cell_Value_2").Range("A1:A3").Value

End Sub

worksheet 3

Step 3: Finally, use the MsgBox function to display the values stored in cell A1: A3.

Code:

Sub VBA_Value_Ex4()

Dim Get_Value_2 As Variant
Get_Value_2 = ThisWorkbook.Worksheets("Getting_Cell_Value_2").Range("A1:A3").Value
MsgBox Get_Value_2

End Sub

work sheet cell value

Step 4: Hit F5 or Run button and see the output for this code.

vba value example 4

You’ll get a Run-time error’13’: Type Mismatch. The reason behind getting this error is, we are defining a single variable and assigning values of a one-dimensional array (with three rows) to it. Which is logically not possible.

This is from this article. Let’s wrap the things up with some points to be remembered.

Things to Remember

You can’t set multiple cells value while using the VBA CELLS method, because it takes rows and columns as arguments. You can only specify the row number and column number in it.

You also can’t get values stored in multiple cells in a single message box. If you have to retrieve the range of values, you need to write the separate get arguments for each of the value.

Recommended Articles

This has been a guide to VBA Value. Here we have discussed how to use Excel VBA Value Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA On Error
  2. VBA Number Format
  3. VBA VLOOKUP
  4. VBA Function

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.

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)

Понравилась статья? Поделить с друзьями:
  • Visual basic excel run time error 1004
  • Visual basic excel online
  • Visual basic excel if cell
  • Visual basic excel array
  • Visual basic excel 2016 скачать