Vba excel text in cell no

I’ve been working with SQL and Excel Macros, but I don’t know how to add text to a cell.

I wish to add the text "01/01/13 00:00" to cell A1. I can’t just write it in the cell because the macro clears the contents of the sheet first and adds the information afterwards.

How do I do that in VBA?

Our Man in Bananas's user avatar

asked Dec 16, 2013 at 13:43

Phil's user avatar

2

Range("$A$1").Value = "'01/01/13 00:00" will do it.

Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.

answered Dec 16, 2013 at 13:44

Bathsheba's user avatar

BathshebaBathsheba

231k33 gold badges359 silver badges477 bronze badges

3

You could do

[A1].Value = "'O1/01/13 00:00"

if you really mean to add it as text (note the apostrophe as the first character).

The [A1].Value is VBA shorthand for Range("A1").Value.

If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):

[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")

answered Dec 16, 2013 at 13:47

Floris's user avatar

FlorisFloris

45.7k6 gold badges70 silver badges122 bronze badges

7

You need to use Range and Value functions.
Range would be the cell where you want the text you want
Value would be the text that you want in that Cell

Range("A1").Value="whatever text"

Manos Nikolaidis's user avatar

answered Mar 7, 2016 at 10:21

Garry's user avatar

GarryGarry

611 silver badge1 bronze badge

You can also use the cell property.

Cells(1, 1).Value = "Hey, what's up?"

Make sure to use a . before Cells(1,1).Value as in .Cells(1,1).Value, if you are using it within With function. If you are selecting some sheet.

enamoria's user avatar

enamoria

8762 gold badges11 silver badges29 bronze badges

answered Dec 19, 2018 at 6:40

Neha Kalani's user avatar

EXPLANATION

This tutorial shows how to test if a cell contains text and return a specified value if the test is True or False by using Excel formulas or VBA.

This tutorial provides three Excel methods that can be applied to test if a cell contains text.

The first method uses a combination of an Excel IF and ISTEXT functions. The ISTEXT function test if the selected cell contains text. If it does then the function will return a TRUE value. The IF function is then used to return a specified value if the ISTEXT function returns a value of TRUE, which in this example is «Contains Text». Alternatively, if the ISTEXT function returns a value of FALSE, then the cell does not contain text and the IF function will return the associated value, which in this example is «No Text».

The second method uses a combination of an Excel IF and ISNUMBER functions. The ISNUMBER function test if the selected cell is a numeric value. If the cell is a numeric value, meaning that there are no text values, then the function will return a TRUE value, alternatively if the cell contains a text value, the function will return a FALSE value. The IF function is then used to return a specified value if the ISNUMBER function returns a value of FALSE, which in this example is «Contains Text». Alternatively, if the ISNUMBER function returns a value of TRUE, then the cell does not contain text and the IF function will return the associated value, which in this example is «No Text».

The third method uses a combination of an Excel IF and COUNTIF functions. The COUNTIF function uses the «*» to identify if the cell contains text. If the cell contains text the COUNTIF function will return a value of 1, alternatively it will return a value of 0. The IF function is then used to return a specified value if the COUNTIF function returns a value greater than 0, which in this example is «Contains Text». Alternatively, if the COUNTIF function returns a value of 0, then the cell does not contain text and the IF function will return the associated value, which in this example is «No Text».

This tutorial provides six VBA methods that can be applied to test if a cell contains text and return a specific value. Methods 1, 3 and 5 are applied against a single cell, whilst methods 2, 4 and 6 use a For Loop to loop through all of the relevant cells, as per the example in the image, to test each of the cells in a range and return specific values. The main difference between the examples is how the code determines is the cell contains text.

FORMULA (using ISTEXT function)
=IF(ISTEXT(value)=TRUE, value_if_true, value_if_false)

FORMULA (using ISNUMBER function)
=IF(ISNUMBER(value)=FALSE, value_if_true, value_if_false)

FORMULA (using COUNTIF function)
=IF(COUNTIF(value, «*»)>0, value_if_true, value_if_false)

ARGUMENTS
value: The value or cell that is to be tested.
value_if_true: Value to be returned if the value or cell contains text.
value_if_false: Value to be returned if the value or cell does not contains text.

Skip to content

Excel Logo

Excel If Cell Contains Text

Excel If Cell Contains Text Then

Excel If Cell Contains Text Then Formula helps you to return the output when a cell have any text or a specific text. You can check if a cell contains a some string or text  and produce something in other cell. For Example you can check if a cell A1 contains text ‘example text’  and print Yes or No in Cell B1. Following are the example Formulas to check if Cell contains text then return some thing in a Cell.

If Cell Contains Text

Here are the Excel formulas to check if Cell contains specific text then return something. This will return if there is any string or any text in given Cell. We can use this simple approach to check if a cell contains text, specific text, string,  any text using Excel If formula. We can use equals to  operator(=) to compare the strings .

If Cell Contains Text Then TRUE

Following is the Excel formula to return True if a Cell contains Specif Text. You can check a cell if there is given string in the Cell and return True or False.

=IF(ISNUMBER(FIND(“How”,A1,1)),TRUE,FALSE)

The formula will return true if it found the match, returns False of no match found.

If Cell Contains Text Then TRUE

If Cell Contains Partial Text

We can return Text If Cell Contains Partial Text. We use formula or VBA to Check Partial Text in a Cell.

Find for Case Sensitive Match:

We can check if a Cell Contains Partial Text then return something using Excel Formula. Following is a simple example to find the partial text in a given Cell. We can use if your want to make the criteria case sensitive.

=IF(ISERROR(FIND($E$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text

  • Here, Find Function returns the finding position of the given string
  • Use Find function is Case Sensitive
  • IsError Function check if Find Function returns Error, that means, string not found

Search for Not Case Sensitive Match:

We can use Search function to check if Cell Contains Partial Text. Search function useful if you want to make the checking criteria Not Case Sensitive.

=IF(ISERROR(SEARCH($F$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text Not Case Sensitive

If Range of Cells Contains Text

We can check for the strings in a range of cells. Here is the formula to find If Range of Cells Contains Text. We can use Count If Formula to check the excel if range of cells contains specific text and return Text.

=IF(COUNTIF(A2:A21, “*Region 1d*”)>0,”Range Contais Text”,”Text Not Found in the Given Range”)
  • CountIf function counts the number of cells with given criteria
  • We can use If function to return the required Text
  • Formula displays the Text ‘Range Contains Text” if match found
  • Returns “Text Not Found in the Given Range” if match not found in the specified range

If Cells Contains Text From List

Below formulas returns text If Cells Contains Text from given List. You can use based on your requirement.

VlookUp to Check If Cell Contains Text from a List:
We can use VlookUp function to match the text in the Given list of Cells. And return the corresponding values.

  • Check if a List Contains Text:
    =IF(ISERR(VLOOKUP(F1,A1:B21,2,FALSE)),”False:Not Contains”,”True: Text Found”)
  • Check if a List Contains Text and Return Corresponding Value:
    =VLOOKUP(F1,A1:B21,2,FALSE)
  • Check if a List Contains Partial Text and Return its Value:
    =VLOOKUP(“*”&F1&”*”,A1:B21,2,FALSE)

If Cell Contains Text Then Return a Value

We can return some value if cell contains some string. Here is the the the Excel formula to return a value if a Cell contains Text. You can check a cell if there is given string in the Cell and return some string or value in another column.

If Cell Contains Text Then Return a Value

=IF(ISNUMBER(SEARCH(“How”,A1,1)),”Found”,”Not Found”)

The formula will return true if it found the match, returns False of no match found. can

Excel if cell contains word then assign value

You can replace any word in the following formula to check if cell contains word then assign value.

=IFERROR(IF(SEARCH(“Word”,A2,1)>0,1,0),””)

Excel if cell contains word then assign value
Search function will check for a given word in the required cell and return it’s position. We can use If function to check if the value is greater than 0 and assign a given value (example: 1) in the cell. search function returns #Value if there is no match found in the cell, we can handle this using IFERROR function.

Count If Cell Contains Text

We can check If Cell Contains Text Then COUNT. Here is the Excel formula to Count if a Cell contains Text. You can count the number of cells containing specific text.

=COUNTIF($A$2:$A$7,”*”&D2&”*”)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then COUNT

Count If Cell Contains Partial Text

We can count the cells based on partial match criteria. The following Excel formula Counts if a Cell contains Partial Text.

=COUNTIF(A2:A21, “*Region 1*”)
  • We can use the CountIf Function to Count the Cells if they contains given String
  • Wild-card operators helps to make the CountIf to check for the Partial String
  • Put Your Text between two asterisk symbols (*YourText*) to make the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to make the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to make the criteria to find your text end of given Cell

If Cell contains text from list then return value

Here is the Excel Formula to check if cell contains text from list then return value. We can use COUNTIF and OR function to check the array of values in a Cell and return the given Value. Here is the formula to check the list in range D2:D5 and check in Cell A2 and return value in B2.

=IF(OR(COUNTIF(A2,”*”&$D$2:$D$5&”*”)), “Return Value”, “”)

Excel If cell contains text from list then return value

If Cell Contains Text Then SUM

Following is the Excel formula to Sum if a Cell contains Text. You can total the cell values if there is given string in the Cell. Here is the example to sum the column B values based on the values in another Column.

=SUMIF($A$2:$A$7,”*”&D2&”*”,$B$2:$B$7)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then SUM

Sum If Cell Contains Partial Text

Use SumIfs function to Sum the cells based on partial match criteria. The following Excel formula Sums the Values if a Cell contains Partial Text.

=SUMIFS(C2:C21,A2:A21, “*Region 1*”)
  • SUMIFS Function will Sum the Given Sum Range
  • We can specify the Criteria Range, and wild-card expression to check for the Partial text
  • Put Your Text between two asterisk symbols (*YourText*) to Sum the Cells if the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to Sum the Cells if the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to Sum the Cells if criteria to find your text end of given Cell

VBA to check if Cell Contains Text

Here is the VBA function to find If Cells Contains Text using Excel VBA Macros.

If Cell Contains Partial Text VBA

We can use VBA to check if Cell Contains Text and Return Value. Here is the simple VBA code match the partial text. Excel VBA if Cell contains partial text macros helps you to use in your procedures and functions.

Sub sbCkeckforPartialText()
MsgBox CheckIfCellContainsPartialText(Cells(2, 1), “Region 1”)
End Sub
Function CheckIfCellContainsPartialText(ByVal cell As Range, ByVal strText As String) As Boolean
If InStr(1, cell.Value, strText) > 0 Then CheckIfCellContainsPartialText = True
End Function
  • CheckIfCellContainsPartialText VBA Function returns true if Cell Contains Partial Text
  • inStr Function will return the Match Position in the given string

If Cell Contains Text Then VBA MsgBox

Here is the simple VBA code to display message box if cell contains text. We can use inStr Function to search for the given string. And show the required message to the user.

Sub sbVBAIfCellsContainsText()
If InStr(1, Cells(2, 1), “Region 3”) > 0 Then blnMatch = True
If blnMatch = True Then MsgBox “Cell Contains Text”
End Sub
  • inStr Function will return the Match Position in the given string
  • blnMatch is the Boolean variable becomes True when match string
  • You can display the message to the user if a Range Contains Text

Which function returns true if cell a1 contains text?

You can use the Excel If function and Find function to return TRUE if Cell A1 Contains Text. Here is the formula to return True.

=IF(ISNUMBER(FIND(“YourText”,A1,1)),TRUE,FALSE)

Which function returns true if cell a1 contains text value?

You can use the Excel If function with Find function to return TRUE if a Cell A1 Contains Text Value. Below is the formula to return True based on the text value.

=IF(ISNUMBER(FIND(“YourTextValue”,A1,1)),TRUE,FALSE)

Share This Story, Choose Your Platform!

7 Comments

  1. Meghana
    December 27, 2019 at 1:42 pm — Reply

    Hi Sir,Thank you for the great explanation, covers everything and helps use create formulas if cell contains text values.

    Many thanks! Meghana!!

  2. Max
    December 27, 2019 at 4:44 pm — Reply

    Perfect! Very Simple and Clear explanation. Thanks!!

  3. Mike Song
    August 29, 2022 at 2:45 pm — Reply

    I tried this exact formula and it did not work.

  4. Theresa A Harding
    October 18, 2022 at 9:51 pm — Reply
  5. Marko
    November 3, 2022 at 9:21 pm — Reply

    Hi

    Is possible to sum all WA11?

    (A1) WA11 4

    (A2) AdBlue 1, WA11 223

    (A3) AdBlue 3, WA11 32, shift 4

    … and everything is in one column.

    Thanks you very much for your help.

    Sincerely Marko

  6. Mike
    December 9, 2022 at 9:59 pm — Reply

    Thank you for the help. The formula =OR(COUNTIF(M40,”*”&Vendors&”*”)) will give “TRUE” when some part of M40 contains a vendor from “Vendors” list. But how do I get Excel to tell which vendor it found in the M40 cell?

    • PNRao
      December 18, 2022 at 6:05 am — Reply

      Please describe your question more elaborately.
      Thanks!

© Copyright 2012 – 2020 | Excelx.com | All Rights Reserved

Page load link

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


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

    20 Step by Step Examples to Search and Find with MacrosIn this Excel VBA Tutorial, you learn how to search and find different items/information with macros.

    This VBA Find Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get free access to this example workbook by clicking the button below.

    Get immediate free access to the Excel VBA Find workbook example

    Use the following Table of Contents to navigate to the Section you’re interested in.

    Related Excel VBA and Macro Training Materials

    The following VBA and Macro training materials may help you better understand and implement the contents below:

    • Tutorials about general VBA constructs and structures:
      • Tutorials for Beginners:
        • Macros.
        • VBA.
      • Enable and disable macros.
      • The Visual Basic Editor (VBE).
      • Procedures:
        • Sub procedures.
        • Function procedures.
      • Work with:
        • Objects.
        • Properties.
        • Methods.
        • Variables.
        • Data types.
        • R1C1-style references.
        • Worksheet functions.
        • Loops.
        • Arrays.
      • Refer to:
        • Sheets and worksheets.
        • Cell ranges.
    • Tutorials with practical VBA applications and macro examples:
      • Find the last row or last column.
      • Set or get a cell’s or cell range’s value.
      • Check if a cell is empty.
      • Use the VLookup function.
    • The comprehensive and actionable Books at The Power Spreadsheets Library:
      • Excel Macros for Beginners Book Series.
      • VBA Fundamentals Book Series.

    #1. Excel VBA Find (Cell with) Value in Cell Range

    VBA Code to Find (Cell with) Value in Cell Range

    To find a cell with a numeric value in a cell range, use the following structure/template in the applicable statement:

    CellRangeObject.Find(What:=SearchedValue, After:=SingleCellRangeObject, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=XlSearchOrderConstant, SearchDirection:=XlSearchDirectionConstant)
    

    The following Sections describe the main elements in this structure.

    CellRangeObject

    A Range object representing the cell range you search in.

    Find

    The Range.Find method:

    • Finds specific information (the numeric value you search for) in a cell range (CellRangeObject).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedValue

    The What parameter of the Range.Find method specifies the data to search for.

    To find a cell with a numeric value in a cell range, set the What parameter to the numeric value you search for (SearchedValue).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the cell range you search in (CellRangeObject).

    If you omit specifying the After parameter, the search begins after the first cell (in the upper left corner) of the cell range you search in (CellRangeObject).

    To find a cell with a numeric value in a cell range, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=xlValues

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find a cell with a numeric value in a cell range, set the LookIn parameter to xlValues. xlValues refers to values.

    LookAt:=xlWhole

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find a cell with a numeric value in a cell range, set the LookAt parameter to xlWhole. xlWhole matches the data you are searching for against the entire/whole searched cell contents.

    SearchOrder:=XlSearchOrderConstant

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (CellRangeObject) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find a cell with a numeric value in a cell range, set the SearchOrder parameter to either of the following, as applicable:

    • xlByRows (SearchOrder:=xlByRows): To search by rows.
    • xlByColumns (SearchOrder:=xlByColumns): To search by columns.
    SearchDirection:=XlSearchDirectionConstant

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find a cell with a numeric value in a cell range, set the SearchDirection parameter to either of the following, as applicable:

    • xlNext (SearchDirection:=xlNext): To search for the next match.
    • xlPrevious (SearchDirection:=xlPrevious): To search for the previous match.

    Macro Example to Find (Cell with) Value in Cell Range

    The following macro (User-Defined Function) example does the following:

    1. Accepts two arguments:
      1. MyRange: The cell range you search in.
      2. MyValue: The numeric value you search for.
    2. Finds MyValue in MyRange.
    3. Returns a string containing the address (as an A1-style relative reference) of the first cell in the cell range (MyRange) where the numeric value (MyValue) is found.
    Function FindValueInCellRange(MyRange As Range, MyValue As Variant) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 2 arguments: MyRange and MyValue
            '(2) Finds a value passed as argument (MyValue) in a cell range passed as argument (MyRange)
            '(3) Returns the address (as an A1-style relative reference) of the first cell in the cell range (MyRange) where the value (MyValue) is found
        
        With MyRange
            FindValueInCellRange = .Find(What:=MyValue, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
        
    End Function
    

    Effects of Executing Macro Example to Find (Cell with) Value in Cell Range

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H30) contain randomly generated values.
    • Cell J7 contains the searched value (41).
    • Cell K7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first cell in the cell range (MyRange) where the numeric value (MyValue) is found. This is cell B11.
    • Cell L7 displays the worksheet formula used in cell K7 (=FindValueInCellRange(A6:H30,J7)).
      • The cell range where the search is carried out contains cells A6 to H30 (A6:H30).
      • The searched value is stored in cell J7 (J7).
    Example: Find value in cell range with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #2. Excel VBA Find (Cell with) Value in Table

    VBA Code to Find (Cell with) Value in Table

    To find a cell with a numeric value in an Excel Table, use the following structure/template in the applicable statement:

    ListObjectObject.DataBodyRange.Find(What:=SearchedValue, After:=SingleCellRangeObject, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=XlSearchOrderConstant, SearchDirection:=XlSearchDirectionConstant)
    

    The following Sections describe the main elements in this structure.

    ListObjectObject

    A ListObject object representing the Excel Table you search in.

    DataBodyRange

    The ListObject.DataBodyRange property returns a Range object representing the cell range containing an Excel Table’s values (excluding the headers).

    Find

    The Range.Find method:

    • Finds specific information (the numeric value you search for) in a cell range (containing the applicable Excel Table’s values).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedValue

    The What parameter of the Range.Find method specifies the data to search for.

    To find a cell with a numeric value in an Excel Table, set the What parameter to the numeric value you search for (SearchedValue).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the cell range you search in (containing the applicable Excel Table’s values).

    If you omit specifying the After parameter, the search begins after the first cell (in the upper left corner) of the cell range you search in (containing the applicable Excel Table’s values).

    To find a cell with a numeric value in an Excel Table, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=xlValues

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find a cell with a numeric value in an Excel Table, set the LookIn parameter to xlValues. xlValues refers to values.

    LookAt:=xlWhole

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find a cell with a numeric value in an Excel Table, set the LookAt parameter to xlWhole. xlWhole matches the data you are searching for against the entire/whole searched cell contents.

    SearchOrder:=XlSearchOrderConstant

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (containing the applicable Excel Table’s values) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find a cell with a numeric value in an Excel Table, set the SearchOrder parameter to either of the following, as applicable:

    • xlByRows (SearchOrder:=xlByRows): To search by rows.
    • xlByColumns (SearchOrder:=xlByColumns): To search by columns.
    SearchDirection:=XlSearchDirectionConstant

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find a cell with a numeric value in an Excel Table, set the SearchDirection parameter to either of the following, as applicable:

    • xlNext (SearchDirection:=xlNext): To search for the next match.
    • xlPrevious (SearchDirection:=xlPrevious): To search for the previous match.

    Macro Example to Find (Cell with) Value in Table

    The following macro (User-Defined Function) example does the following:

    1. Accepts 3 arguments:
      1. MyWorksheetName: The name of the worksheet where the Excel Table you search in is stored.
      2. MyValue: The numeric value you search for.
      3. MyTableIndex: The index number of the Excel Table (stored in the worksheet named MyWorksheetName) you search in. MyTableIndex is an optional argument with a default value of 1.
    2. Finds MyValue in the applicable Excel Table’s values (excluding the headers).
    3. Returns a string containing the address (as an A1-style relative reference) of the first cell in the applicable Excel Table where the numeric value (MyValue) is found.
    Function FindValueInTable(MyWorksheetName As String, MyValue As Variant, Optional MyTableIndex As Long = 1) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 3 arguments: MyWorksheetName, MyValue and MyTableIndex
            '(2) Finds a value passed as argument (MyValue) in an Excel Table stored in a worksheet whose name is passed as argument (MyWorksheetName). The index number of the Excel Table is either:
                '(1) Passed as an argument (MyTableIndex); or
                '(2) Assumed to be 1 (if MyTableIndex is omitted)
            '(3) Returns the address (as an A1-style relative reference) of the first cell in the Excel Table (stored in the MyWorksheetName worksheet and whose index is MyTableIndex) where the value (MyValue) is found
        
        With ThisWorkbook.Worksheets(MyWorksheetName).ListObjects(MyTableIndex).DataBodyRange
            FindValueInTable = .Find(What:=MyValue, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
        
    End Function
    

    Effects of Executing Macro Example to Find (Cell with) Value in Table

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H31) contain an Excel Table with randomly generated values.
    • Cell J7 contains the searched value (41).
    • Cell K7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first cell in the Excel Table where the numeric value (MyValue) is found. This is cell B12.
    • Cell L7 displays the worksheet formula used in cell K7 (=FindValueInTable(“Find Value in Table”,J7)).
      • The name of the worksheet where the Excel Table is stored is “Find Value in Table” (“Find Value in Table”).
      • The searched value is stored in cell J7 (J7).
      • The index number of the Excel Table is 1 (by default).
    Example: Find value in table with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #3. Excel VBA Find (Cell with) Value in Column

    VBA Code to Find (Cell with) Value in Column

    To find a cell with a numeric value in a column, use the following structure/template in the applicable statement:

    RangeObjectColumn.Find(What:=SearchedValue, After:=SingleCellRangeObject, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=XlSearchDirectionConstant)
    

    The following Sections describe the main elements in this structure.

    RangeObjectColumn

    A Range object representing the column you search in.

    Find

    The Range.Find method:

    • Finds specific information (the numeric value you search for) in a cell range (RangeObjectColumn).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedValue

    The What parameter of the Range.Find method specifies the data to search for.

    To find a cell with a numeric value in a column, set the What parameter to the numeric value you search for (SearchedValue).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the column you search in (RangeObjectColumn).

    If you omit specifying the After parameter, the search begins after the first cell of the column you search in (RangeObjectColumn).

    To find a cell with a numeric value in a column, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=xlValues

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find a cell with a numeric value in a column, set the LookIn parameter to xlValues. xlValues refers to values.

    LookAt:=xlWhole

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find a cell with a numeric value in a column, set the LookAt parameter to xlWhole. xlWhole matches the data you are searching for against the entire/whole searched cell contents.

    SearchOrder:=xlByRows

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable column (RangeObjectColumn) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find a cell with a numeric value in a column, set the SearchOrder parameter to xlByRows. xlByRows results in the Range.Find method searching by rows.

    SearchDirection:=XlSearchDirectionConstant

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find a cell with a numeric value in a column, set the SearchDirection parameter to either of the following, as applicable:

    • xlNext (SearchDirection:=xlNext): To search for the next match.
    • xlPrevious (SearchDirection:=xlPrevious): To search for the previous match.

    Macro Example to Find (Cell with) Value in Column

    The following macro (User-Defined Function) example does the following:

    1. Accepts two arguments:
      1. MyColumn: The column you search in.
      2. MyValue: The numeric value you search for.
    2. Finds MyValue in MyColumn.
    3. Returns a string containing the address (as an A1-style relative reference) of the first cell in the column (MyColumn) where the numeric value (MyValue) is found.
    Function FindValueInColumn(MyColumn As Range, MyValue As Variant) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 2 arguments: MyColumn and MyValue
            '(2) Finds a value passed as argument (MyValue) in a column passed as argument (MyColumn)
            '(3) Returns the address (as an A1-style relative reference) of the first cell in the column (MyColumn) where the value (MyValue) is found
        
        With MyColumn
            FindValueInColumn = .Find(What:=MyValue, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
        
    End Function
    

    Effects of Executing Macro Example to Find (Cell with) Value in Column

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column A (cells A6 to A31) contains randomly generated values.
    • Cell C7 contains the searched value (90).
    • Cell D7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first cell in the column (MyColumn) where the numeric value (MyValue) is found. This is cell A13.
    • Cell E7 displays the worksheet formula used in cell D7 (=FindValueInColumn(A:A,C7)).
      • The column where the search is carried out is column A (A:A).
      • The searched value is stored in cell C7 (C7).

    Get immediate free access to the Excel VBA Find workbook example

    #4. Excel VBA Find (Cell with) Value in Table Column

    VBA Code to Find (Cell with) Value in Table Column

    To find a cell with a numeric value in an Excel Table column, use the following structure/template in the applicable statement:

    ListColumnObject.DataBodyRange.Find(What:=SearchedValue, After:=SingleCellRangeObject, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=XlSearchOrderConstant, SearchDirection:=XlSearchDirectionConstant)
    

    The following Sections describe the main elements in this structure.

    ListColumnObject

    A ListColumn object representing the Excel Table column you search in.

    DataBodyRange

    The ListColumn.DataBodyRange property returns a Range object representing the cell range containing an Excel Table column’s values (excluding the header).

    Find

    The Range.Find method:

    • Finds specific information (the numeric value you search for) in a cell range (containing the applicable Excel Table column’s values).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedValue

    The What parameter of the Range.Find method specifies the data to search for.

    To find a cell with a numeric value in an Excel Table column, set the What parameter to the numeric value you search for (SearchedValue).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the cell range you search in (containing the applicable Excel Table column’s values).

    If you omit specifying the After parameter, the search begins after the first cell of the cell range you search in (containing the applicable Excel Table column’s values).

    To find a cell with a numeric value in an Excel Table column, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=xlValues

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find a cell with a numeric value in an Excel Table column, set the LookIn parameter to xlValues. xlValues refers to values.

    LookAt:=xlWhole

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find a cell with a numeric value in an Excel Table column, set the LookAt parameter to xlWhole. xlWhole matches the data you are searching for against the entire/whole searched cell contents.

    SearchOrder:=XlSearchOrderConstant

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (containing the applicable Excel Table column’s values) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find a cell with a numeric value in an Excel Table column, set the SearchOrder parameter to either of the following, as applicable:

    • xlByRows (SearchOrder:=xlByRows): To search by rows.
    • xlByColumns (SearchOrder:=xlByColumns): To search by columns.
    SearchDirection:=XlSearchDirectionConstant

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find a cell with a numeric value in an Excel Table column, set the SearchDirection parameter to either of the following, as applicable:

    • xlNext (SearchDirection:=xlNext): To search for the next match.
    • xlPrevious (SearchDirection:=xlPrevious): To search for the previous match.

    Macro Example to Find (Cell with) Value in Table Column

    The following macro (User-Defined Function) example does the following:

    1. Accepts 4 arguments:
      1. MyWorksheetName: The name of the worksheet where the Excel Table (containing the column you search in) is stored.
      2. MyColumnIndex: The index/column number of the column you search in (in the applicable Excel Table).
      3. MyValue: The numeric value you search for.
      4. MyTableIndex: The index number of the Excel Table (stored in the worksheet named MyWorksheetName) containing the column you search in. MyTableIndex is an optional argument with a default value of 1.
    2. Finds MyValue in the applicable Excel Table column’s values (excluding the header).
    3. Returns a string containing the address (as an A1-style relative reference) of the first cell in the applicable Excel Table column where the numeric value (MyValue) is found.
    Function FindValueInTableColumn(MyWorksheetName As String, MyColumnIndex As Long, MyValue As Variant, Optional MyTableIndex As Long = 1) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 4 arguments: MyWorksheetName, MyColumnIndex, MyValue and MyTableIndex
            '(2) Finds a value passed as argument (MyValue) in an Excel Table column, where:
                '(1) The table column's index is passed as argument (MyColumnIndex); and
                '(2) The Excel Table is stored in a worksheet whose name is passed as argument (MyWorksheetName). The index number of the Excel Table is either:
                    '(1) Passed as an argument (MyTableIndex); or
                    '(2) Assumed to be 1 (if MyTableIndex is omitted)
            '(3) Returns the address (as an A1-style relative reference) of the first cell in the applicable Excel Table column where the value (MyValue) is found
        
        With ThisWorkbook.Worksheets(MyWorksheetName).ListObjects(MyTableIndex).ListColumns(MyColumnIndex).DataBodyRange
            FindValueInTableColumn = .Find(What:=MyValue, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
        
    End Function
    

    Effects of Executing Macro Example to Find (Cell with) Value in Table Column

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H31) contain an Excel Table with randomly generated values. Cells in the first row (row 7) contain the searched value (90), except for the cell in the searched column (Column 3).
    • Cell J7 contains the searched value (90).
    • Cell K7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first cell in the applicable Excel Table column (Column 3) where the numeric value (MyValue) is found. This is cell C14.
    • Cell L7 displays the worksheet formula used in cell K7 (=FindValueInTableColumn(“Find Value in Table Column”,3, J7)).
      • The name of the worksheet where the Excel Table is stored is “Find Value in Table Column” (“Find Value in Table Column”).
      • The index number of the Excel Table column is 3 (3).
      • The searched value is stored in cell J7 (J7).
      • The index number of the Excel Table is 1 (by default).
    Example: Find value in table column with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #5. Excel VBA Find Minimum Value in Cell Range

    VBA Code to Find Minimum Value in Cell Range

    To find the minimum value in a cell range, use the following structure/template in the applicable statement:

    Application.Min(CellRangeObject)
    

    The following Sections describe the main elements in this structure.

    Application.Min

    The WorksheetFunction.Min method returns the minimum value in a set of values.

    CellRangeObject

    The WorksheetFunction.Min method accepts up to thirty parameters (Arg1 to Arg30). These are the values for which you want to find the minimum value.

    To find the minimum value in a cell range, pass a Range object (CellRangeObject) representing the cell range whose minimum value you want to find as method parameter.

    Macro Example to Find Minimum Value in Cell Range

    The following macro (User-Defined Function) example does the following:

    1. Accepts 1 argument (MyRange): The cell range whose minimum value you search for.
    2. Finds and returns the minimum value in the cell range (MyRange).
    Function FindMinimumValueInCellRange(MyRange As Range) As Double
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 1 argument: MyRange
            '(2) Finds the minimum value in the cell range passed as argument (MyRange)
        
        FindMinimumValueInCellRange = Application.Min(MyRange)
    
    End Function
    

    Effects of Executing Macro Example to Find Minimum Value in Cell Range

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H30) contain randomly generated values.
    • Cell J7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the minimum value in the cell range (MyRange). This is the number 1.
    • Cell K7 displays the worksheet formula used in cell J7 (=FindMinimumValueInCellRange(A6:H30)). The cell range where the search is carried out contains cells A6 to H30 (A6:H30).
    Example: Find minimum value in cell range with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #6. Excel VBA Find (Cell with) String (or Text) in Cell Range

    VBA Code to Find (Cell with) String (or Text) in Cell Range

    To find a cell with a string (or text) in a cell range, use the following structure/template in the applicable statement:

    CellRangeObject.Find(What:=SearchedString, After:=SingleCellRangeObject, LookIn:=XlFindLookInConstant, LookAt:=XlLookAtConstant, SearchOrder:=XlSearchOrderConstant, SearchDirection:=XlSearchDirectionConstant, MatchCase:=BooleanValue)
    

    The following Sections describe the main elements in this structure.

    CellRangeObject

    A Range object representing the cell range you search in.

    Find

    The Range.Find method:

    • Finds specific information (the string or text you search for) in a cell range (CellRangeObject).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedString

    The What parameter of the Range.Find method specifies the data to search for.

    To find a cell with a string (or text) in a cell range, set the What parameter to the string (or text) you search for (SearchedString).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the cell range you search in (CellRangeObject).

    If you omit specifying the After parameter, the search begins after the first cell (in the upper left corner) of the cell range you search in (CellRangeObject).

    To find a cell with a string (or text) in a cell range, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=XlFindLookInConstant

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find a cell with a string (or text) in a cell range, set the LookIn parameter to either of the following, as applicable:

    • xlFormulas (LookIn:=xlFormulas): To search in the applicable cell range’s formulas.
    • xlValues (LookIn:=xlValues): To search in the applicable cell range’s values.
    LookAt:=XlLookAtConstant

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find a cell with a string (or text) in a cell range, set the LookAt parameter to either of the following, as applicable:

    • xlWhole (LookAt:=xlWhole): To match against the entire/whole searched cell contents.
    • xlPart (LookAt:=xlPart): To match against any part of the searched cell contents.
    SearchOrder:=XlSearchOrderConstant

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (CellRangeObject) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find a cell with a string (or text) in a cell range, set the SearchOrder parameter to either of the following, as applicable:

    • xlByRows (SearchOrder:=xlByRows): To search by rows.
    • xlByColumns (SearchOrder:=xlByColumns): To search by columns.
    SearchDirection:=XlSearchDirectionConstant

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find a cell with a string (or text) in a cell range, set the SearchDirection parameter to either of the following, as applicable:

    • xlNext (SearchDirection:=xlNext): To search for the next match.
    • xlPrevious (SearchDirection:=xlPrevious): To search for the previous match.
    MatchCase:=BooleanValue

    The MatchCase parameter of the Range.Find method specifies whether the search is:

    • Case-sensitive; or
    • Case-insensitive.

    The default value of the MatchCase parameter is False.

    To find a cell with a string (or text) in a cell range, set the MatchCase parameter to either of the following, as applicable:

    • True (MatchCase:=True): To carry out a case-sensitive search.
    • False (MatchCase:=False): To carry out a case-insensitive search.

    Macro Example to Find (Cell with) String (or Text) in Cell Range

    The following macro (User-Defined Function) example does the following:

    1. Accepts two arguments:
      1. MyRange: The cell range you search in.
      2. MyString: The string (or text) you search for.
    2. Finds MyString in MyRange. The search is case-insensitive.
    3. Returns a string containing the address (as an A1-style relative reference) of the first cell in the cell range (MyRange) where the string or text (MyString) is found.
    Function FindStringInCellRange(MyRange As Range, MyString As Variant) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 2 arguments: MyRange and MyString
            '(2) Finds a string passed as argument (MyString) in a cell range passed as argument (MyRange). The search is case-insensitive
            '(3) Returns the address (as an A1-style relative reference) of the first cell in the cell range (MyRange) where the string (MyString) is found
        
        With MyRange
            FindStringInCellRange = .Find(What:=MyString, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
        
    End Function
    

    Effects of Executing Macro Example to Find (Cell with) String (or Text) in Cell Range

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H30) contain randomly generated words.
    • Cell J7 contains the searched string or text (Excel).
    • Cell K7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first cell in the cell range (MyRange) where the string or text (MyString) is found. This is cell F20.
    • Cell L7 displays the worksheet formula used in cell K7 (=FindStringInCellRange(A6:H30,J7)).
      • The cell range where the search is carried out contains cells A6 to H30 (A6:H30).
      • The searched string or text is stored in cell J7 (J7).
    Example: Find String in cell range with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #7. Excel VBA Find (Cell with) String (or Text) in Column

    VBA Code to Find (Cell with) String (or Text) in Column

    To find a cell with a string (or text) in a column, use the following structure/template in the applicable statement:

    RangeObjectColumn.Find(What:=SearchedString, After:=SingleCellRangeObject, LookIn:=XlFindLookInConstant, LookAt:=XlLookAtConstant, SearchOrder:=xlByRows, SearchDirection:=XlSearchDirectionConstant, MatchCase:=BooleanValue)
    

    The following Sections describe the main elements in this structure.

    RangeObjectColumn

    A Range object representing the column you search in.

    Find

    The Range.Find method:

    • Finds specific information (the string or text you search for) in a cell range (RangeObjectColumn).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedString

    The What parameter of the Range.Find method specifies the data to search for.

    To find a cell with a string (or text) in a column, set the What parameter to the string (or text) you search for (SearchedString).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the column you search in (RangeObjectColumn).

    If you omit specifying the After parameter, the search begins after the first cell of the column you search in (RangeObjectColumn).

    To find a cell with a string (or text) in a column, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=XlFindLookInConstant

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find a cell with a string (or text) in a column, set the LookIn parameter to either of the following, as applicable:

    • xlFormulas (LookIn:=xlFormulas): To search in the applicable column’s formulas.
    • xlValues (LookIn:=xlValues): To search in the applicable column’s values.
    LookAt:=XlLookAtConstant

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find a cell with a string (or text) in a column, set the LookAt parameter to either of the following, as applicable:

    • xlWhole (LookAt:=xlWhole): To match against the entire/whole searched cell contents.
    • xlPart (LookAt:=xlPart): To match against any part of the searched cell contents.
    SearchOrder:=xlByRows

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable column (RangeObjectColumn) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find a cell with a string (or text) in a column, set the SearchOrder parameter to xlByRows. xlByRows results in the Range.Find method searching by rows.

    SearchDirection:=XlSearchDirectionConstant

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find a cell with a string (or text) in a column, set the SearchDirection parameter to either of the following, as applicable:

    • xlNext (SearchDirection:=xlNext): To search for the next match.
    • xlPrevious (SearchDirection:=xlPrevious): To search for the previous match.
    MatchCase:=BooleanValue

    The MatchCase parameter of the Range.Find method specifies whether the search is:

    • Case-sensitive; or
    • Case-insensitive.

    The default value of the MatchCase parameter is False.

    To find a cell with a string (or text) in a column, set the MatchCase parameter to either of the following, as applicable:

    • True (MatchCase:=True): To carry out a case-sensitive search.
    • False (MatchCase:=False): To carry out a case-insensitive search.

    Macro Example to Find (Cell with) String (or Text) in Column

    The following macro (User-Defined Function) example does the following:

    1. Accepts two arguments:
      1. MyColumn: The column you search in.
      2. MyString: The string (or text) you search for.
    2. Finds MyString in MyColumn. The search is case-insensitive.
    3. Returns a string containing the address (as an A1-style relative reference) of the first cell in the column (MyColumn) where the string or text (MyString) is found.
    Function FindStringInColumn(MyColumn As Range, MyString As Variant) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 2 arguments: MyColumn and MyString
            '(2) Finds a string passed as argument (MyString) in a column passed as argument (MyColumn). The search is case-insensitive
            '(3) Returns the address (as an A1-style relative reference) of the first cell in the column (MyColumn) where the string (MyString) is found
        
        With MyColumn
            FindStringInColumn = .Find(What:=MyString, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
        
    End Function
    

    Effects of Executing Macro Example to Find (Cell with) String (or Text) in Column

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column A (cells A6 to A30) contains randomly generated words.
    • Cell C7 contains the searched string or text (Excel).
    • Cell D7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first cell in the column (MyColumn) where the string or text (MyString) is found. This is cell A21.
    • Cell E7 displays the worksheet formula used in cell D7 (=FindStringInColumn(A:A,C7)).
      • The column where the search is carried out is column A (A:A).
      • The searched string or text is stored in cell C7 (C7).
    Example: Find string in column with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #8. Excel VBA Find String (or Text) in Cell

    VBA Code to Find String (or Text) in Cell

    To find a string (or text) in a cell, use the following structure/template in the applicable statement:

    InStr(StartingPosition, SearchedCell.Value, SearchedString, VbCompareMethodConstant)
    

    The following Sections describe the main elements in this structure.

    InStr

    The InStr function returns a number. This number specifies the position of the first occurrence of a string or text (SearchedString) in another string (the string stored in SearchedCell).

    StartingPosition

    The Start argument of the InStr function is:

    • An optional argument.
    • A numeric expression specifying the starting position for the string (or text) search.

    If you omit specifying the Start argument, the search begins at the first character of the searched string (the string stored in SearchedCell).

    To find a string (or text) in a cell, set the Start argument to the position (in the string stored in SearchedCell) where the string (or text) search starts.

    SearchedCell.Value

    The String1 argument of the InStr function represents the string expression the InStr function searches in.

    To find a string (or text) in a cell, set the String1 argument to the value/string stored in the searched cell. For these purposes:

    • “SearchedCell” is a Range object representing the searched cell.
    • “Value” refers to the Range.Value property. The Range.Value property returns the value/string stored in the searched cell (SearchedCell).
    SearchedString

    The String2 argument of the InStr function represents the string expression (or text) the InStr function searches for.

    To find a string (or text) in a cell, set the String2 argument to the string (or text) you search for.

    VbCompareMethodConstant

    The Compare argument of the InStr function:

    • Is an optional argument.
    • Specifies the type of string comparison carried out by the InStr function.
    • Can take any of the built-in constants/values from the vbCompareMethod enumeration.

    If you omit specifying the Compare argument, the type of string comparison is determined by the Option Compare statement. The Option Compare statement declares the default string comparison method at a module level. The default string comparison method is binary (vbBinaryCompare).

    To find a string (or text) in a cell, set the Compare argument to either of the following, as applicable:

    • vbBinaryCompare: Performs a binary comparison. vbBinaryCompare:
      • Results in a case-sensitive search.
      • May be (slightly) faster than vbTextCompare.
    • vbTextCompare: Performs a textual comparison. vbTextCompare:
      • Results in a case-insensitive search.
      • May be (slightly) slower than vbBinaryCompare.
      • Is more prone to errors/bugs than vbBinaryCompare.

    Macro Example to Find String (or Text) in Cell

    The following macro (User-Defined Function) example does the following:

    1. Accepts three arguments:
      1. MyCell: The cell you search in.
      2. MyString: The string (or text) you search for.
      3. MyStartingPosition: The starting position for the string (or text) search. MyStartingPosition is an optional argument with a default value of 1.
    2. Finds MyString in the value/string stored in MyCell.
    3. Returns the following:
      1. If MyString is not found in the value/string stored in MyCell, the string “String not found in cell”.
      2. If MyString is found in the value/string stored in MyCell, the position of the first occurrence of MyString in the value/string stored in MyCell.
    Function FindStringInCell(MyCell As Range, MyString As Variant, Optional MyStartingPosition As Variant = 1) As Variant
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts three arguments: MyCell, MyString and MyStartingPosition (optional argument with a default value of 1)
            '(2) Finds a string passed as argument (MyString) in the value/string stored in a cell passed as argument (MyCell)
            '(3) Returns the following (as applicable):
                'If MyString is not found in the value/string stored in MyCell: The string "String not found in cell"
                'If MyString is found in the value/string stored in MyCell: The position of the first occurrence of MyString in the value/string stored in MyCell
        
        'Obtain position of first occurrence of MyString in the value/string stored in MyCell
        FindStringInCell = InStr(MyStartingPosition, MyCell.Value, MyString, vbBinaryCompare)
        
        'If MyString is not found in the value/string stored in MyCell, return the string "String not found in cell"
        If FindStringInCell = 0 Then FindStringInCell = "String not found in cell"
    
    End Function
    

    Effects of Executing Macro Example to Find String (or Text) in Cell

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column A (cells A7 to A31) contains randomly generated words.
    • Column B (cells B7 to B31) contains a 2-character string (ar).
    • Column C (cells C7 to C31) contains worksheet formulas working with the macro (User-Defined Function) example. These worksheet formulas return either of the following (as applicable):
      • The string “String not found in cell”, if the string (or text) specified in the applicable cell of column B is not found in the applicable cell of column A.
      • The position of the first occurrence of the string (or text) specified in the applicable cell of column B in the applicable cell of column A, if the string (or text) specified in the applicable cell of column B is found in the applicable cell of column A.
    • Column D (cells D7 to D31) displays the worksheet formulas used in column C (=FindStringInCell(CellInColumnA,CellInColumnB)).
      • The cell where the search is carried out is in column A (CellInColumnA).
      • The searched string or text is stored in column B (CellInColumnB).
    Example: Find string in cell with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #9. Excel VBA Find String (or Text) in String

    VBA Code to Find String (or Text) in String

    To find a string (or text) in a string, use the following structure/template in the applicable statement:

    InStr(StartingPosition, SearchedString, SearchedText, VbCompareMethodConstant)
    

    The following Sections describe the main elements in this structure.

    InStr

    The InStr function returns a number. This number specifies the position of the first occurrence of a string or text (SearchedText) in another string (SearchedString).

    StartingPosition

    The Start argument of the InStr function is:

    • An optional argument.
    • A numeric expression specifying the starting position for the string (or text) search.

    If you omit specifying the Start argument, the search begins at the first character of the searched string (SearchedString).

    To find a string (or text) in a string, set the Start argument to the position (in SearchedString) where the string (or text) search starts.

    SearchedString

    The String1 argument of the InStr function represents the string expression the InStr function searches in.

    To find a string (or text) in a string, set the String1 argument to the searched string.

    SearchedText

    The String2 argument of the InStr function represents the string expression (or text) the InStr function searches for.

    To find a string (or text) in a string, set the String2 argument to the string (or text) you search for.

    VbCompareMethodConstant

    The Compare argument of the InStr function:

    • Is an optional argument.
    • Specifies the type of string comparison carried out by the InStr function.
    • Can take any of the built-in constants/values from the vbCompareMethod enumeration.

    If you omit specifying the Compare argument, the type of string comparison is determined by the Option Compare statement. The Option Compare statement declares the default string comparison method at a module level. The default string comparison method is binary (vbBinaryCompare).

    To find a string (or text) in a string, set the Compare argument to either of the following, as applicable:

    • vbBinaryCompare: Performs a binary comparison. vbBinaryCompare:
      • Results in a case-sensitive search.
      • May be (slightly) faster than vbTextCompare.
    • vbTextCompare: Performs a textual comparison. vbTextCompare:
      • Results in a case-insensitive search.
      • May be (slightly) slower than vbBinaryCompare.
      • Is more prone to errors/bugs than vbBinaryCompare.

    Macro Example to Find String (or Text) in String

    The following macro (User-Defined Function) example does the following:

    1. Accepts three arguments:
      1. MyString: The string you search in.
      2. MyText: The string (or text) you search for.
      3. MyStartingPosition: The starting position for the string (or text) search. MyStartingPosition is an optional argument with a default value of 1.
    2. Finds MyText in MyString.
    3. Returns the following:
      1. If MyText is not found in MyString, the string “Text not found in string”.
      2. If MyText is found in MyString, the position of the first occurrence of MyText in MyString.
    Function FindTextInString(MyString As Variant, MyText As Variant, Optional MyStartingPosition As Variant = 1) As Variant
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts three arguments: MyString, MyText and MyStartingPosition (optional argument with a default value of 1)
            '(2) Finds text (a string) passed as argument (MyText) in a string passed as argument (MyString)
            '(3) Returns the following (as applicable):
                'If MyText is not found in MyString: The string "Text not found in string"
                'If MyText is found in MyString: The position of the first occurrence of MyText in MyString
        
        'Obtain position of first occurrence of MyText in MyString
        FindTextInString = InStr(MyStartingPosition, MyString, MyText, vbBinaryCompare)
        
        'If MyText is not found in MyString, return the string "Text not found in string"
        If FindTextInString = 0 Then FindTextInString = "Text not found in string"
    
    End Function
    

    Effects of Executing Macro Example to Find String (or Text) in String

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column A (cells A7 to A31) contains randomly generated words.
    • Column B (cells B7 to B31) contains text (at).
    • Column C (cells C7 to C31) contains worksheet formulas working with the macro (User-Defined Function) example. These worksheet formulas return either of the following (as applicable):
      • The string “Text not found in string”, if the string (or text) specified in the applicable cell of column B is not found in the string specified in the applicable cell of column A.
      • The position of the first occurrence of the string (or text) specified in the applicable cell of column B in the string specified in the applicable cell of column A, if the string (or text) specified in the applicable cell of column B is found in the string specified in the applicable cell of column A.
    • Column D (cells D7 to D31) displays the worksheet formulas used in column C (=FindTextInString(CellInColumnA,CellInColumnB)).
      • The string where the search is carried out is stored in column A (CellInColumnA).
      • The searched string (or text) is stored in column B (CellInColumnB).
    Example: Find text in string with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #10. Excel VBA Find Character in String

    VBA Code to Find Character in String

    To find a character in a string, use the following structure/template in the applicable statement:

    InStr(StartingPosition, SearchedString, SearchedCharacter, VbCompareMethodConstant)
    

    The following Sections describe the main elements in this structure.

    InStr

    The InStr function returns a number. This number specifies the position of the first occurrence of a string or text (SearchedCharacter) in another string (SearchedString).

    StartingPosition

    The Start argument of the InStr function is:

    • An optional argument.
    • A numeric expression specifying the starting position for the character search.

    If you omit specifying the Start argument, the search begins at the first character of the searched string (SearchedString).

    To find a character in a string, set the Start argument to the position (in SearchedString) where the character search starts.

    SearchedString

    The String1 argument of the InStr function represents the string expression the InStr function searches in.

    To find a character in a string, set the String1 argument to the searched string.

    SearchedCharacter

    The String2 argument of the InStr function represents the string expression (or text) the InStr function searches for.

    To find a character in a string, set the String2 argument to the character you search for.

    VbCompareMethodConstant

    The Compare argument of the InStr function:

    • Is an optional argument.
    • Specifies the type of string comparison carried out by the InStr function.
    • Can take any of the built-in constants/values from the vbCompareMethod enumeration.

    If you omit specifying the Compare argument, the type of string comparison is determined by the Option Compare statement. The Option Compare statement declares the default string comparison method at a module level. The default string comparison method is binary (vbBinaryCompare).

    To find a character in a string, set the Compare argument to either of the following, as applicable:

    • vbBinaryCompare: Performs a binary comparison. vbBinaryCompare:
      • Results in a case-sensitive search.
      • May be (slightly) faster than vbTextCompare.
    • vbTextCompare: Performs a textual comparison. vbTextCompare:
      • Results in a case-insensitive search.
      • May be (slightly) slower than vbBinaryCompare.
      • Is more prone to errors/bugs than vbBinaryCompare.

    Macro Example to Find Character in String

    The following macro (User-Defined Function) example does the following:

    1. Accepts three arguments:
      1. MyString: The string you search in.
      2. MyCharacter: The character you search for.
      3. MyStartingPosition: The starting position for the character search. MyStartingPosition is an optional argument with a default value of 1.
    2. Finds MyCharacter in MyString.
    3. Returns the following:
      1. If MyCharacter is not found in MyString, the string “Character not found in string”.
      2. If MyCharacter is found in MyString, the position of the first occurrence of MyCharacter in MyString.
    Function FindCharacterInString(MyString As Variant, MyCharacter As Variant, Optional MyStartingPosition As Variant = 1) As Variant
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts three arguments: MyString, MyCharacter and MyStartingPosition (optional argument with a default value of 1)
            '(2) Finds a character passed as argument (MyCharacter) in a string passed as argument (MyString)
            '(3) Returns the following (as applicable):
                'If MyCharacter is not found in MyString: The string "Character not found in string"
                'If MyCharacter is found in MyString: The position of the first occurrence of MyCharacter in MyString
        
        'Obtain position of first occurrence of MyCharacter in MyString
        FindCharacterInString = InStr(MyStartingPosition, MyString, MyCharacter, vbBinaryCompare)
        
        'If MyCharacter is not found in MyString, return the string "Character not found in string"
        If FindCharacterInString = 0 Then FindCharacterInString = "Character not found in string"
    
    End Function
    

    Effects of Executing Macro Example to Find Character in String

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column A (cells A7 to A31) contains randomly generated words.
    • Column B (cells B7 to B31) contains a character (a).
    • Column C (cells C7 to C31) contains worksheet formulas working with the macro (User-Defined Function) example. These worksheet formulas return either of the following (as applicable):
      • The string “Character not found in string”, if the character specified in the applicable cell of column B is not found in the string specified in the applicable cell of column A.
      • The position of the first occurrence of the character specified in the applicable cell of column B in the string specified in the applicable cell of column A, if the character specified in the applicable cell of column B is found in the string specified in the applicable cell of column A.
    • Column D (cells D7 to D31) displays the worksheet formulas used in column C (=FindCharacterInString(CellInColumnA,CellInColumnB)).
      • The string where the search is carried out is stored in column A (CellInColumnA).
      • The searched character is stored in column B (CellInColumnB).
    Example: Find character in string with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #11. Excel VBA Find Column with Specific Header

    VBA Code to Find Column with Specific Header

    To find a column with a specific header, use the following structure/template in the applicable statement:

    HeaderRowRangeObject.Find(What:=SearchedHeader, After:=SingleCellRangeObject, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=XlSearchDirectionConstant, MatchCase:=BooleanValue)
    

    The following Sections describe the main elements in this structure.

    HeaderRowRangeObject

    A Range object representing the cell range containing the headers you search in.

    Find

    The Range.Find method:

    • Finds specific information (the header you search for) in a cell range (HeaderRowRangeObject).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedHeader

    The What parameter of the Range.Find method specifies the data to search for.

    To find a column with a specific header, set the What parameter to the header you search for (SearchedHeader).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the cell range containing the headers you search in (HeaderRowRangeObject).

    If you omit specifying the After parameter, the search begins after the first cell of the cell range you search in (HeaderRowRangeObject).

    To find a column with a specific header, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=xlValues

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find a column with a specific header, set the LookIn parameter to xlValues. xlValues refers to values.

    LookAt:=xlWhole

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find a column with a specific header, set the LookAt parameter to xlWhole. xlWhole matches the data you are searching for against the entire/whole searched cell contents.

    SearchOrder:=xlByColumns

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (HeaderRowRangeObject) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find a column with a specific header, set the SearchOrder parameter to xlByColumns. xlByColumns searches by columns.

    SearchDirection:=XlSearchDirectionConstant

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find a column with a specific header, set the SearchDirection parameter to either of the following, as applicable:

    • xlNext (SearchDirection:=xlNext): To search for the next match.
    • xlPrevious (SearchDirection:=xlPrevious): To search for the previous match.
    MatchCase:=BooleanValue

    The MatchCase parameter of the Range.Find method specifies whether the search is:

    • Case-sensitive; or
    • Case-insensitive.

    The default value of the MatchCase parameter is False.

    To find a column with a specific header, set the MatchCase parameter to either of the following, as applicable:

    • True (MatchCase:=True): To carry out a case-sensitive search.
    • False (MatchCase:=False): To carry out a case-insensitive search.

    Macro Example to Find Column with Specific Header

    The following macro (User-Defined Function) example does the following:

    1. Accepts two arguments:
      1. MyRange: The cell range whose first row contains the headers you search in.
      2. MyHeader: The header you search for.
    2. Finds MyHeader in the first row of MyRange.
    3. Returns the number of the column containing the first cell in the header row where the header (MyHeader) is found.
    Function FindColumnWithSpecificHeader(MyRange As Range, MyHeader As Variant) As Long
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 2 arguments: MyRange and MyHeader
            '(2) Finds a header passed as argument (MyHeader) in the first row (the header row) of a cell range passed as argument (MyRange). The search is case-insensitive
            '(3) Returns the number of the column containing the first cell in the header row where the header (MyHeader) is found
        
        With MyRange.Rows(1)
            FindColumnWithSpecificHeader = .Find(What:=MyHeader, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
        End With
    
    End Function
    

    Effects of Executing Macro Example to Find Column with Specific Header

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H31) contain data with the following characteristics:
      • Headers in its first row (row 6).
      • Randomly generated values.
    • Cell J7 contains the searched header (Column 3).
    • Cell K7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the column number of the first cell in the header row (cells A6 to H6) of the cell range (MyRange) where the header (MyHeader) is found. This is column 3 (C).
    • Cell L7 displays the worksheet formula used in cell K7 (=FindColumnWithSpecificHeader(A6:H31,J7)).
      • The cell range whose first row contains the headers where the search is carried out contains cells A6 to H31 (A6:H31).
      • The searched header is stored in cell J7 (J7).
    Example: Find column with specific header with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #12. Excel VBA Find Next or Find All

    VBA Code to Find Next or Find All

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, use the following structure/template in the applicable procedure:

    Dim FoundCell As Range
    Dim FirstFoundCellAddress As String
    Set FoundCell = SearchedRangeObject.Find(What:=SearchedData, After:=SingleCellRangeObject, LookIn:=XlFindLookInConstant, LookAt:=XlLookAtConstant, SearchOrder:=XlSearchDirectionConstant, SearchDirection:=xlNext, MatchCase:=BooleanValue)
    If Not FoundCell Is Nothing Then
        FirstFoundCellAddress = FoundCell.Address
        Do
            Statements
            Set FoundCell = SearchedRangeObject.FindNext(After:=FoundCell)
        Loop Until FoundCell.Address = FirstFoundCellAddress
    End If
    

    The following Sections describe the main elements in this structure.

    Lines #1 and #2: Dim FoundCell As Range | Dim FirstFoundCellAddress As String

    Dim

    The Dim statement:

    1. Declares variables.
    2. Allocates storage space.
    FoundCell | FirstFoundCellAddress

    The names of the variables declared with the Dim statement.

    • FoundCell holds/represents the cell where the searched data is found.
    • FirstFoundCellAddress holds/represents the address of the first cell where the searched data is found.
    As Range | As String

    The data type of the variables declared with the Dim statement.

    • FoundCell is of the Range object data type. The Range object represents a cell or cell range.
    • FirstFoundCellAddress is of the String data type. The String data type (generally) holds textual data.

    Line #3: Set FoundCell = SearchedRangeObject.Find(What:=SearchedData, After:=SingleCellRangeObject, LookIn:=XlFindLookInConstant, LookAt:=XlLookAtConstant, SearchOrder:=XlSearchDirectionConstant, SearchDirection:=xlNext, MatchCase:=BooleanValue)

    Set

    The Set statement assigns an object reference to an object variable.

    FoundCell

    Object variable holding/representing the cell where the searched data is found.

    =

    The assignment operator assigns an object reference (returned by the Range.Find method) to an object variable (FoundCell).

    SearchedRangeObject

    A Range object representing the cell range you search in.

    Find

    The Range.Find method:

    • Finds specific information (the data you search for) in a cell range (SearchedRangeObject).
    • Returns a Range object representing the first cell where the information is found.
    What:=SearchedData

    The What parameter of the Range.Find method specifies the data to search for.

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the What parameter to the data you search for (SearchedData).

    After:=SingleCellRangeObject

    The After parameter of the Range.Find method specifies the cell after which the search begins. This must be a single cell in the cell range you search in (SearchedRangeObject).

    If you omit specifying the After parameter, the search begins after the first cell (in the upper left corner) of the cell range you search in (SearchedRangeObject).

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the After parameter to a Range object representing the cell after which the search begins.

    LookIn:=XlFindLookInConstant

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the LookIn parameter to any of the following, as applicable:

    • xlCommentsThreaded (LookIn:=xlCommentsThreaded): To search in the applicable cell range’s threaded comments.
    • xlValues (LookIn:=xlValues): To search in the applicable cell range’s values.
    • xlComments (LookIn:=xlComments): To search in the applicable cell range’s comments/notes.
    • xlFormulas (LookIn:=xlFormulas): To search in the applicable cell range’s formulas.
    LookAt:=XlLookAtConstant

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the LookAt parameter to either of the following, as applicable:

    • xlWhole (LookAt:=xlWhole): To match against the entire/whole searched cell contents.
    • xlPart (LookAt:=xlPart): To match against any part of the searched cell contents.
    SearchOrder:=XlSearchDirectionConstant

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (SearchedRangeObject) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the SearchOrder parameter to either of the following, as applicable:

    • xlByRows (SearchOrder:=xlByRows): To search by rows.
    • xlByColumns (SearchOrder:=xlByColumns): To search by columns.
    SearchDirection:=xlNext

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the SearchDirection parameter to xlNext. xlNext results in the Range.Find method searching for the next match.

    MatchCase:=BooleanValue

    The MatchCase parameter of the Range.Find method specifies whether the search is:

    • Case-sensitive; or
    • Case-insensitive.

    The default value of the MatchCase parameter is False.

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the MatchCase parameter to either of the following, as applicable:

    • True (MatchCase:=True): To carry out a case-sensitive search.
    • False (MatchCase:=False): To carry out a case-insensitive search.

    Lines #4 and 10: If Not FoundCell Is Nothing Then | End If

    If … Then | End If

    The If… Then… Else statement:

    • Conditionally executes a set of statements (lines #5 to #9);
    • Depending on an expression’s value (Not FoundCell Is Nothing).
    Not FoundCell Is Nothing

    The condition of an If… Then… Else statement is an expression evaluating to True or False. If the expression returns True, the applicable set of statements (lines #5 to #9) is executed.

    In this expression:

    • Not FoundCell:
      • The Not operator performs a logical negation on an expression.
      • FoundCell is the object variable holding/representing the cell where the searched data is found.
      • The Range.Find method (in line #3) returns Nothing if no match is found. Therefore:
        • If the Range.Find method finds no match:
          • FoundCell is Nothing.
          • Not FoundCell is not Nothing.
        • If the Range.Find method finds a match:
          • FoundCell is not Nothing.
          • Not FoundCell is Nothing.
    • Is: The Is operator is an object reference comparison operator.
    • Nothing: Nothing allows you to disassociate a variable from the data it previously represented. The Range.Find method (in line #3) returns Nothing if no match is found.

    Line #5: FirstFoundCellAddress = FoundCell.Address

    FirstFoundCellAddress

    Variable holding/representing the address of the first cell where the searched data is found.

    =

    The assignment operator assigns the result returned by an expression (FoundCell.Address) to a variable (FirstFoundCellAddress).

    FoundCell

    Object variable holding/representing the cell where the searched data is found.

    At this point, FoundCell holds/represents the first cell where the searched data is found (by line #3).

    Address

    The Range.Address property returns a String representing the applicable cell range’s (FoundCell’s) reference.

    Lines #6 and #9: Do | Loop Until FoundCell.Address = FirstFoundCellAddress

    Do | Loop Until…

    The Do… Loop Until statement repeats a set of statements until a condition becomes True.

    FoundCell.Address = FirstFoundCellAddress

    The condition of a Do… Loop Until statement is an expression evaluating to True or False. The applicable set of statements (lines #7 and #8) are:

    1. (Always) executed once, even if the condition is never met; and
    2. Repeatedly executed until the condition returns True.

    In this expression:

    • FoundCell.Address:
      • FoundCell is an object variable holding/representing the cell where the searched data is found.
      • The Range.Address property returns a String representing the applicable cell range’s (FoundCell’s) reference.
    • =: The equal to comparison operator returns True or False as follows:
      • True if both expressions (FoundCell.Address and FirstFoundCellAddress) are equal.
      • False if the expressions (FoundCell.Address and FirstFoundCellAddress) are not equal.
    • FirstFoundCellAddress: Variable holding/representing the address of the first cell where the searched data is found.

    This condition is tested (only) after the procedure finds (and works with) the first cell where the searched data is found. Therefore, the condition (only) returns True after the Range.FindNext method (line #8) wraps around to the first cell where the searched data is found (after finding all other cells where the searched data is found).

    Line #7: Statements

    Set of statements to be repeatedly executed for each cell where the searched data is found.

    Line #8: Set FoundCell = SearchedRangeObject.FindNext(After:=FoundCell)

    Set

    The Set statement assigns an object reference to an object variable.

    FoundCell

    Object variable holding/representing the cell where the searched data is found.

    =

    The assignment operator assigns an object reference (returned by the Range.FindNext method) to an object variable (FoundCell).

    SearchedRangeObject

    A Range object representing the cell range you search in.

    FindNext

    The Range.FindNext method:

    • Continues the search that was begun by the Range.Find method (line #3).
    • Finds the next cell matching the conditions specified by the Range.Find method (line #3).
    • Returns a Range object representing the next cell where the information is found.
    After:=FoundCell

    The After parameter of the Range.FindNext method specifies the cell after which the search restarts.

    To (i) find the next appearance of specific information or (ii) find all appearances of specific information, set the After parameter to the object variable holding/representing the cell where the searched data is found.

    Macro Example to Find Next or Find All

    The following macro example does the following:

    1. Find:
      1. All cells whose value is 10;
      2. In the cell range containing cells A6 to H30 in the “Find Next All” worksheet in the workbook where the procedure is stored.
    2. Set the interior/fill color of all found cells to light green.
    Sub FindNextAll()
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This procedure:
            '(1) Finds all cells whose value is 10 in cells A6 to H30 of the "Find Next All" worksheet in this workbook
            '(2) Sets the found cells' interior/fill color to light green
        
        'Declare variable to hold/represent searched value
        Dim MyValue As Long
        
        'Declare variable to hold/represent address of first cell where searched value is found
        Dim FirstFoundCellAddress As String
        
        'Declare object variable to hold/represent cell range where search takes place
        Dim MyRange As Range
        
        'Declare object variable to hold/represent cell where searched value is found
        Dim FoundCell As Range
        
        'Specify searched value
        MyValue = 10
        
        'Identify cell range where search takes place
        Set MyRange = ThisWorkbook.Worksheets("Find Next All").Range("A6:H30")
        
        'Find first cell where searched value is found
        With MyRange
            Set FoundCell = .Find(What:=MyValue, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
        End With
        
        'Test whether searched value is found in cell range where search takes place
        If Not FoundCell Is Nothing Then
            
            'Store address of first cell where searched value is found
            FirstFoundCellAddress = FoundCell.Address
            
            Do
                
                'Set interior/fill color of applicable cell where searched value is found to light green
                FoundCell.Interior.Color = RGB(63, 189, 133)
                
                'Find next cell where searched value is found
                Set FoundCell = MyRange.FindNext(After:=FoundCell)
            
            'Loop until address of current cell where searched value is found is equal to address of first cell where searched value was found
            Loop Until FoundCell.Address = FirstFoundCellAddress
        
        End If
        
    End Sub
    

    Effects of Executing Macro Example to Find Next or Find All

    The following image illustrates the effects of executing the macro example. In this example:

    • Cells A6 to H30 contain randomly generated values.
    • A text box (Find all cells where value = 10) executes the macro example when clicked.

    After the macro is executed, Excel sets the interior/fill color of all cells whose value is 10 to light green.

    Example: Find next appearance or find all appearances with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #13. Excel VBA Find Last Row with Data in Cell Range

    VBA Code to Find Last Row with Data in Cell Range

    To find the last row with data in a cell range, use the following structure/template in the applicable procedure:

    If Application.CountA(SearchedCellRangeObject) = 0 Then
        LastRowVariable = ValueIfCellRangeEmpty
    Else
        LastRowVariable = SearchedCellRangeObject.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
    

    The following Sections describe the main elements in this structure.

    Lines #1, #3 and #5: If Application.CountA(SearchedCellRangeObject) = 0 Then | Else | End If

    If… Then … Else… End If

    The If… Then… Else statement:

    1. Conditionally executes a set of statements (line #2 or line #4);
    2. Depending on an expression’s value (Application.CountA(SearchedCellRangeObject) = 0).
    Application.CountA(SearchedCellRangeObject) = 0

    The condition of an If… Then… Else statement is an expression evaluating to True or False.

    • If the expression returns True, a set of statements (line #2) is executed.
    • If the expression returns False, a different set of statements (line #4) is executed.

    In this expression:

    • Application.CountA(…): The WorksheetFunction.CountA method counts the number of cells in a cell range (SearchedCellRangeObject) that are not empty.
    • SearchedCellRangeObject: A Range object representing the cell range whose last row you search.
    • =: The equal to comparison operator returns True or False as follows:
      • True if both expressions (Application.CountA(SearchedCellRangeObject) and 0) are equal.
      • False if the expressions (Application.CountA(SearchedCellRangeObject) and 0) are not equal.
    • 0: The number 0. The WorksheetFunction.CountA method returns 0 if all cells in SearchedCellRangeObject are empty.

    Line #2: LastRowVariable = ValueIfCellRangeEmpty

    Assignment statement assigning:

    • ValueIfCellRangeEmpty; to
    • LastRowVariable.

    In this expression:

    • LastRowVariable: Variable of (usually) the Long data type holding/representing the number of the last row with data in the cell range whose last row you search (SearchedCellRangeObject).
    • =: Assignment operator. Assigns a value (ValueIfCellRangeEmpty) to a variable (LastRowVariable).
    • ValueIfCellRangeEmpty: Value assigned to LastRowVariable when SearchedCellRangeObject is empty and the WorksheetFunction.CountA method returns 0.

    Line #4: LastRowVariable = SearchedCellRangeObject.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    LastRowVariable

    Variable of (usually) the Long data type holding/representing the number of the last row with data in the cell range whose last row you search (SearchedCellRangeObject).

    =

    The assignment operator assigns a value (SearchedCellRangeObject.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row) to a variable (LastRowVariable).

    SearchedCellRangeObject

    A Range object representing the cell range whose last row you search.

    Find

    The Range.Find method:

    • Finds specific information in a cell range (SearchedCellRangeObject).
    • Returns a Range object representing the first cell where the information is found.
    What:=”*”

    The What parameter of the Range.Find method specifies the data to search for.

    To find the last row with data in a cell range, set the What parameter to any character sequence. The asterisk (*) acts as a wildcard and results in Range.Find searching for any character sequence.

    LookIn:=xlFormulas

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find the last row with data in a cell range, set the LookIn parameter to xlFormulas. xlFormulas refers to formulas.

    LookAt:=xlPart

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find the last row with data in a cell range, set the LookAt parameter to xlPart. xlPart matches the data you are searching for (any character sequence as specified by the What parameter) against any part of the searched cell contents.

    SearchOrder:=xlByRows

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (SearchedCellRangeObject) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find the last row with data in a cell range, set the SearchOrder parameter to xlByRows. xlByRows results in the Range.Find method searching by rows.

    SearchDirection:=xlPrevious

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find the last row with data in a cell range, set the SearchDirection parameter to xlPrevious. xlPrevious results in the Range.Find method searching for the previous match.

    Row

    The Range.Row property returns the number of the first row of the first area in a cell range.

    When searching for the last row with data in a cell range, the Range.Row property returns the row number of the cell represented by the Range object returned by the Range.Find method (Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious)).

    Macro Example to Find Last Row with Data in Cell Range

    The following macro (User-Defined Function) example does the following:

    1. Accepts one argument (MyRange). This is the cell range whose last row you search.
    2. Tests whether MyRange is empty and proceeds accordingly:
      1. If MyRange is empty, returns the number 0 as the number of the last row with data in MyRange.
      2. If MyRange isn’t empty:
        1. Finds the last row with data in MyRange; and
        2. Returns the number of the last row with data in MyRange.
    Function FindLastRow(MyRange As Range) As Long
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 1 argument: MyRange
            '(2) Tests whether MyRange is empty
            '(3) If MyRange is empty, returns 0 as the number of the last row with data in MyRange
            '(4) If MyRange is not empty:
                '(1) Finds the last row with data in MyRange by searching for the last cell with any character sequence
                '(2) Returns the number of the last row with data in MyRange
            
        'Test if MyRange is empty
        If Application.CountA(MyRange) = 0 Then
    
            'If MyRange is empty, assign 0 to FindLastRow
            FindLastRow = 0
    
        Else
        
            'If MyRange isn't empty, find the last cell with any character sequence by:
                '(1) Searching for the previous match;
                '(2) Across rows
            FindLastRow = MyRange.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    
        End If
        
    End Function
    

    Effects of Executing Macro Example to Find Last Row with Data in Cell Range

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H30) contain data.
    • Cell J7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the number of the last row with data in the cell range (MyRange). This is row 30.
    • Cell K7 displays the worksheet formula used in cell J7 (=FindLastRow(A:H)). The cell range whose last row is searched contains columns A through H (A:H).
    Example: Find last row with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #14. Excel VBA Find Last Column with Data in Cell Range

    VBA Code to Find Last Column with Data in Cell Range

    To find the last column with data in a cell range, use the following structure/template in the applicable procedure:

    If Application.CountA(SearchedCellRangeObject) = 0 Then
        LastColumnVariable = ValueIfCellRangeEmpty
    Else
        LastColumnVariable = SearchedCellRangeObject.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    End If
    

    The following Sections describe the main elements in this structure.

    Lines #1, #3 and #5: If Application.CountA(SearchedCellRangeObject) = 0 Then | Else | End If

    If… Then … Else… End If

    The If… Then… Else statement:

    1. Conditionally executes a set of statements (line #2 or line #4);
    2. Depending on an expression’s value (Application.CountA(SearchedCellRangeObject) = 0).
    Application.CountA(SearchedCellRangeObject) = 0

    The condition of an If… Then… Else statement is an expression evaluating to True or False.

    • If the expression returns True, a set of statements (line #2) is executed.
    • If the expression returns False, a different set of statements (line #4) is executed.

    In this expression:

    • Application.CountA(…): The WorksheetFunction.CountA method counts the number of cells in a cell range (SearchedCellRangeObject) that are not empty.
    • SearchedCellRangeObject: A Range object representing the cell range whose last column you search.
    • =: The equal to comparison operator returns True or False as follows:
      • True if both expressions (Application.CountA(SearchedCellRangeObject) and 0) are equal.
      • False if the expressions (Application.CountA(SearchedCellRangeObject) and 0) are not equal.
    • 0: The number 0. The WorksheetFunction.CountA method returns 0 if all cells in SearchedCellRangeObject are empty.

    Line #2: LastColumnVariable = ValueIfCellRangeEmpty

    Assignment statement assigning:

    • ValueIfCellRangeEmpty; to
    • LastColumnVariable.

    In this expression:

    • LastColumnVariable: Variable of (usually) the Long data type holding/representing the number of the last column with data in the cell range whose last column you search (SearchedCellRangeObject).
    • =: Assignment operator. Assigns a value (ValueIfCellRangeEmpty) to a variable (LastColumnVariable).
    • ValueIfCellRangeEmpty: Value assigned to LastColumnVariable when SearchedCellRangeObject is empty and the WorksheetFunction.CountA method returns 0.

    Line #4: LastColumnVariable = SearchedCellRangeObject.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

    LastColumnVariable

    Variable of (usually) the Long data type holding/representing the number of the last column with data in the cell range whose last column you search (SearchedCellRangeObject).

    =

    The assignment operator assigns a value (SearchedCellRangeObject.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column) to a variable (LastColumnVariable).

    SearchedCellRangeObject

    A Range object representing the cell range whose last column you search.

    Find

    The Range.Find method:

    • Finds specific information in a cell range (SearchedCellRangeObject).
    • Returns a Range object representing the first cell where the information is found.
    What:=”*”

    The What parameter of the Range.Find method specifies the data to search for.

    To find the last column with data in a cell range, set the What parameter to any character sequence. The asterisk (*) acts as a wildcard and results in Range.Find searching for any character sequence.

    LookIn:=xlFormulas

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find the last column with data in a cell range, set the LookIn parameter to xlFormulas. xlFormulas refers to formulas.

    LookAt:=xlPart

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • Can take any of the built-in constants/values from the XlLookAt enumeration.

    To find the last column with data in a cell range, set the LookAt parameter to xlPart. xlPart matches the data you are searching for (any character sequence as specified by the What parameter) against any part of the searched cell contents.

    SearchOrder:=xlByColumns

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (SearchedCellRangeObject) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find the last column with data in a cell range, set the SearchOrder parameter to xlByColumns. xlByColumns results in the Range.Find method searching by columns.

    SearchDirection:=xlPrevious

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find the last column with data in a cell range, set the SearchDirection parameter to xlPrevious. xlPrevious results in the Range.Find method searching for the previous match.

    Column

    The Range.Column property returns the number of the first column of the first area in a cell range.

    When searching for the last column with data in a cell range, the Range.Column property returns the column number of the cell represented by the Range object returned by the Range.Find method (Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)).

    Macro Example to Find Last Column with Data in Cell Range

    The following macro (User-Defined Function) example does the following:

    1. Accepts one argument (MyWorksheetName). This is the name of the worksheet whose last column you search.
    2. Tests whether the worksheet named MyWorksheetName is empty and proceeds accordingly:
      1. If the worksheet named MyWorksheetName is empty, returns the number 0 as the number of the last column with data in the worksheet.
      2. If the worksheet named MyWorksheetName isn’t empty:
        1. Finds the last column with data in the worksheet; and
        2. Returns the number of the last column with data in the worksheet.
    Function FindLastColumn(MyWorksheetName As String) As Long
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 1 argument: MyWorksheetName
            '(2) Tests whether the worksheet named MyWorksheetName is empty
            '(3) If the worksheet named MyWorksheetName is empty, returns 0 as the number of the last column with data in the worksheet
            '(4) If the worksheet named MyWorksheetName is not empty:
                '(1) Finds the last column with data in the worksheet by searching for the last cell with any character sequence
                '(2) Returns the number of the last column with data in the worksheet
        
        'Declare object variable to hold/represent all cells in the worksheet named MyWorksheetName
        Dim MyRange As Range
        
        'Identify all cells in the worksheet named MyWorksheetName
        Set MyRange = ThisWorkbook.Worksheets(MyWorksheetName).Cells
        
        'Test if MyRange is empty
        If Application.CountA(MyRange) = 0 Then
    
            'If MyRange is empty, assign 0 to FindLastColumn
            FindLastColumn = 0
    
        Else
        
            'If MyRange isn't empty, find the last cell with any character sequence by:
                '(1) Searching for the previous match;
                '(2) Across columns
            FindLastColumn = MyRange.Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    
        End If
        
    End Function
    

    Effects of Executing Macro Example to Find Last Column with Data in Cell Range

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H30) in the worksheet named “Find Last Column Data” contain data.
      • Columns A through H of the “Find Last Column Data” worksheet contain exactly the same data as that in the “Find Last Column Formula” worksheet (displayed in the image below).
      • The “Find Last Column Data” worksheet contains no data in columns J or K whereas the “Find Last Column Formula” worksheet (displayed in the image below) does.
    • Cell J7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the number of the last column with data in the worksheet (named “Find Last Column Data”). This is column H or 8.
    • Cell K7 displays the worksheet formula used in cell J7 (=FindLastColumn(“Find Last Column Data”)). The name of the worksheet whose last column is searched is “Find Last Column Data”.

    Get immediate free access to the Excel VBA Find workbook example

    #15. Excel VBA Find Last Non Empty Cell in Column

    VBA Code to Find Last Non Empty Cell in Column

    To find the last non empty cell in a column, use the following structure/template in the applicable statement:

    WorksheetObject.Range(ColumnLetter & WorksheetObject.Rows.Count).End(xlUp)
    

    The following Sections describe the main elements in this structure.

    WorksheetObject

    A Worksheet object representing the worksheet containing the column whose last non empty cell you want to find.

    Range

    The Worksheet.Range property returns a Range object representing a cell or cell range.

    ColumnLetter

    The letter of the column whose last non empty cell you want to find.

    &

    The concatenation operator joins two strings and creates a new string.

    WorksheetObject

    A Worksheet object representing the worksheet containing the column whose last non empty cell you want to find.

    Rows

    The Worksheet.Rows property returns a Range object representing all rows in the applicable worksheet (containing the column whose last non empty cell you want to find).

    Count

    The Range.Count property returns the number of objects in a collection (the number of rows in the worksheet containing the column whose last non empty cell you want to find).

    End(xlUp)

    The Range.End property returns a Range object representing the cell at the end of the region containing the source range. In other words: The Range.End property is the rough equivalent of using the “Ctrl + Arrow Key” or “End, Arrow Key” keyboard shortcuts.

    The Range.End property accepts one parameter: Direction. Direction:

    • Specifies the direction in which to move.
    • Can take the any of the built-in constants/values from the XlDirection enumeration.

    To find the last non empty cell in a column, set the Direction parameter to xlUp. xlUp:

    • Results in moving up, to the top of the data region.
    • Is the rough equivalent of the “Ctrl + Up Arrow” or “End, Up Arrow” keyboard shortcuts.

    Macro Example to Find Last Non Empty Cell in Column

    The following macro (User-Defined Function) example does the following:

    1. Accepts one argument (MyColumn): The letter of the column (in the worksheet where the UDF is used) whose last non empty cell you want to find.
    2. Finds the last non empty cell in the applicable column.
    3. Returns a string containing the address (as an A1-style relative reference) of the last non empty cell in the applicable column.
    Function FindLastNonEmptyCellColumn(MyColumn As String) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 1 argument: MyColumn
            '(2) Finds the last non empty cell in the column whose letter is passed as argument (MyColumn) in the worksheet where the UDF is used
            '(3) Returns the address (as an A1-style relative reference) of the last non empty cell found in the column whose letter is passed as argument (MyColumn) in the worksheet where the UDF is used
        With Application.Caller.Parent
            FindLastNonEmptyCellColumn = .Range(MyColumn & .Rows.Count).End(xlUp).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
    
    End Function
    

    Effects of Executing Macro Example to Find Last Non Empty Cell in Column

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column A (cells A6 to A30) contains data.
    • Cell C7 contains the letter of the column whose last non empty cell is sought (A).
    • Cell D7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the last non empty cell in column A (MyColumn). This is cell A30
    • Cell E7 displays the worksheet formula used in cell D7 (=FindLastNonEmptyCellColumn(C7)). The letter of the column whose last non empty cell is sought is stored in cell C7 (C7).
    Example: Find last non empty cell in column with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #16. Excel VBA Find Empty (or Blank) Cells

    VBA Code to Find Empty (or Blank) Cells

    To find all empty (or blank) cells in a cell range, use the following structure/template in the applicable procedure:

    Dim BlankCellsObjectVariable As Range
    On Error Resume Next
    Set BlankCellsObjectVariable = RangeObjectWithBlankCells.SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0
    If Not BlankCellsObjectVariable Is Nothing Then
        StatementsIfBlankCells
    End If
    

    The following Sections describe the main elements in this structure.

    Line #1: Dim BlankCellsObjectVariable As Range

    Dim

    The Dim statement:

    1. Declares variables.
    2. Allocates storage space.
    BlankCellsObjectVariable

    The name of the variable declared with the Dim statement.

    BlankCellsObjectVariable holds/represents the empty (or blank) cells found.

    As Range

    The data type of the variable declared with the Dim statement.

    BlankCellsObjectVariable is declared as of the Range object data type. The Range object represents a cell or cell range.

    Line #2: On Error Resume Next

    The On Error Resume Next statement specifies that, when a run-time error occurs, control passes to the statement immediately following that statement where the error occurred. Therefore, procedure execution continues.

    Line #3 returns an error (Run time error ‘1004′: No cells were found) if the cell range where you search for empty (or blank) cells doesn’t contain any empty (or blank) cells.

    Line #3: Set BlankCellsObjectVariable = RangeObjectWithBlankCells.SpecialCells(xlCellTypeBlanks)

    Set

    The Set statement assigns an object reference to an object variable.

    BlankCellsObjectVariable

    Object variable holding/representing the empty (or blank) cells found.

    =

    The assignment operator assigns an object reference (returned by the Range.SpecialCells method) to an object variable (BlankCellsObjectVariable).

    RangeObjectWithBlankCells

    A Range object representing the cell range you search in for empty (or blank) cells.

    SpecialCells

    The Range.SpecialCells method returns a Range object representing all cells matching a specified:

    • Type; and
    • Value.
    xlCellTypeBlanks

    The Type parameter of the Range.SpecialCells method:

    • Specifies the cells to include in the Range object returned by the Range.SpecialCells method.
    • Can take any of the built-in constants/values from the XlCellType enumeration.

    To find all empty (or blank) cells in a cell range, set the Type parameter to xlCellTypeBlanks. xlCellTypeBlanks results in the Range.SpecialCells method including blank/empty cells in the Range object it returns.

    Line #4: On Error GoTo 0

    The On Error GoTo 0 statement disables error handling (originally enabled by line #2).

    Line #5 and #7: If Not BlankCellsObjectVariable Is Nothing Then | End If

    If… Then | End If

    The If… Then… Else statement:

    • Conditionally executes a set of statements (line #6);
    • Depending on an expression’s value (Not BlankCellsObjectVariable Is Nothing).
    Not BlankCellsObjectVariable Is Nothing

    The condition of an If… Then… Else statement is an expression evaluating to True or False. If the expression returns True, the applicable set of statements (line #6) is executed.

    In this expression:

    • Not BlankCellsObjectVariable:
      • The Not operator performs a logical negation on an expression.
      • BlankCellsObjectVariable is the object variable holding/representing the empty (or blank) cells found.
      • BlankCellsObjectVariable holds/represents Nothing if no empty (or blank) cells are found. Therefore:
        • If the Range.SpecialCells method finds no empty (or blank) cells:
          • BlankCellsObjectVariable is Nothing.
          • Not BlankCellsObjectVariable is not Nothing.
        • If the Range.SpecialCells method finds empty (or blank) cells:
          • BlankCellsObjectVariable is not Nothing.
          • Not BlankCellsObjectVariable is Nothing.
    • Is: The Is operator is an object reference comparison operator.
    • Nothing: Nothing allows you to disassociate a variable from the data it previously represented. BlankCellsObjectVariable holds/represents Nothing if no empty (or blank) cells are found.

    Line #6: StatementsIfBlankCells

    Statements conditionally executed by the If… Then… Else statement if the applicable condition (Not BlankCellsObjectVariable Is Nothing) returns True (the Range.SpecialCells method finds empty or blank cells).

    Macro Example to Find Empty (or Blank) Cells

    The following macro example does the following:

    1. Find all empty (or blank) cells in the cell range containing cells A6 to H30 in the “Find Blank Cells” worksheet in the workbook where the procedure is stored.
    2. Set the interior/fill color of all found empty (or blank) cells to light green.
    Sub FindBlankCells()
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This procedure:
            '(1) Finds all blank cells in cells A6 to H30 of the "Find Blank Cells" worksheet in this workbook
            '(2) Sets the found cells' interior/fill color to light green
        
        'Declare object variable to hold/represent blank cells
        Dim MyBlankCells As Range
            
        'Enable error-handling
        On Error Resume Next
        
        'Identify blank cells in searched cell range
        Set MyBlankCells = ThisWorkbook.Worksheets("Find Blank Cells").Range("A6:H30").SpecialCells(xlCellTypeBlanks)
        
        'Disable error-handling
        On Error GoTo 0
        
        'Test whether blank cells were found in searched cell range
        If Not MyBlankCells Is Nothing Then
            
            'Set interior/fill color of blank cells found to light green
            MyBlankCells.Interior.Color = RGB(63, 189, 133)
            
        End If
    
    End Sub
    

    Effects of Executing Macro Example to Find Empty (or Blank) Cells

    The following image illustrates the effects of using the macro example. In this example:

    • Columns A through H (cells A6 to H30) contain:
      • Data; and
      • A few empty cells (with light green interior/fill).
    • A text box (Find all blank cells) executes the macro example when clicked.

    After the macro is executed, Excel sets the interior/fill color of all empty (or blank) cells to light green.

    Example: Find blank cells with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #17. Excel VBA Find First Empty (or Blank) Cell in Cell Range

    VBA Code to Find First Empty (or Blank) Cell in Cell Range

    To find the first empty (or blank) cell in a cell range, use the following structure/template in the applicable procedure:

    For Each iCell In CellRangeObject
        If IsEmpty(iCell) Then
            StatementsForFirstEmptyCell
            Exit For
        End If
    Next iCell
    

    The following Sections describe the main elements in this structure.

    Lines #1 and #6: For Each iCell In CellRangeObject | Next iCell

    For Each … In … | Next …

    The For Each… Next statement repeats a series of statements for each element (iCell, an individual cell) in a collection (CellRangeObject).

    iCell

    Object variable (of the Range data type) used to iterate/loop through each element of the collection (CellRangeObject).

    CellRangeObject

    A Range object representing the cell range you search in.

    The series of statements repeated by the For Each… Next statement are repeated for each individual element (iCell) in CellRangeObject.

    Lines #2 and #5: If IsEmpty(iCell) Then | End If

    If… Then | End If

    The If… Then Else statement:

    • Conditionally executes a set of statements (lines #3 and #4);
    • Depending on an expression’s value (IsEmpty(iCell)).
    IsEmpty(iCell)

    The condition of an If… Then… Else statement is an expression evaluating to True or False. If the expression returns True, the applicable set of statements (lines #3 and #4) are executed.

    In this expression:

    • As a general rule, the IsEmpty function returns a Boolean value (True or False) indicating whether a variable is initialized. You can (also) use the IsEmpty function to test whether a cell is empty (or blank).
    • iCell is an object variable representing the individual cell the For Each… Next statement is currently working with (iterating through).
    • IsEmpty(iCell) returns True or False as follows:
      • True if the cell (currently) represented by iCell is empty (or blank).
      • False if the cell (currently) represented by iCell isn’t empty. A cell isn’t considered to be empty if, for example, it contains a worksheet formula returning a zero-length string (“”).

    Line #3: StatementsForFirstEmptyCell

    Statements conditionally executed by the If… Then… Else statement if the applicable condition (IsEmpty(iCell)) returns True (the cell currently represented by iCell is empty or blank).

    Line #4: Exit For

    The Exit For statement:

    • Exits a For Each… Next loop.
    • Transfers control to the statement following the Next statement (line #6).

    Macro Example to Find First Empty (or Blank) Cell in Cell Range

    The following macro (User-Defined Function) example does the following:

    1. Accepts one argument (MyRange): The cell range whose first empty cell you search for.
    2. Loops through each individual cell in the cell range (MyRange) and tests whether the applicable cell is empty (or blank).
    3. Returns the following:
      1. If MyRange contains empty cells, the address (as an A1-style relative reference) of the first empty cell in the cell range (MyRange).
      2. If MyRange doesn’t contain empty cells, the string “No empty cells found in cell range”.
    Function FindNextEmptyCellRange(MyRange As Range) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 1 argument: MyRange
            '(2) Loops through each individual cell in the cell range (MyRange) and tests whether the applicable cell is empty
            '(3) Returns the following (as applicable):
                'If there are empty cells in MyRange: The address (as an A1-style relative reference) of the first empty cell
                'If there are no empty cells in MyRange: The string "No empty cells found in cell range"
        
        'Declare object variable to iterate/loop through all cells in the cell range (MyRange)
        Dim iCell As Range
        
        'Loop through each cell in the cell range (MyRange)
        For Each iCell In MyRange
            
            'If the current cell is empty:
                '(1) Return the current cell's address (as an A1-style relative reference)
                '(2) Exit the For Each... Next loop
            If IsEmpty(iCell) Then
                FindNextEmptyCellRange = iCell.Address(RowAbsolute:=False, ColumnAbsolute:=False)
                Exit For
            End If
            
        Next iCell
        
        'If no empty cells are found in the cell range (MyRange), return the string "No empty cells found in cell range"
        If FindNextEmptyCellRange = "" Then FindNextEmptyCellRange = "No empty cells found in cell range"
    
    End Function
    

    Effects of Executing Macro Example to Find First Empty (or Blank) Cell in Cell Range

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Columns A through H (cells A6 to H30) contain:
      • Data; and
      • A few empty cells (with light green interior/fill).
    • Cell J7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first empty cell in the cell range (MyRange). This is cell B7.
    • Cell K7 displays the worksheet formula used in cell J7 (=FindNextEmptyCellRange(A6:H30)). The cell range where the search is carried out contains cells A6 to H30 (A6:H30).
    Example: Find first empty cell in cell range with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #18. Excel VBA Find First Empty (or Blank) Cell in Column

    VBA Code to Find First Empty (or Blank) Cell in Column

    To find the first empty (or blank) cell in a column, use the following structure/template in the applicable statement:

    ColumnRangeObject.Find(What:="", After:=ColumnRangeObject.Cells(ColumnRangeObject.Cells.Count), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
    

    The following Sections describe the main elements in this structure.

    ColumnRangeObject

    A Range object representing the column whose first empty (or blank) cell you search for.

    Find

    The Range.Find method:

    • Finds specific information (the first empty or blank cell) in a cell range (ColumnRangeObject).
    • Returns a Range object representing the first cell where the information is found.
    What:=””

    The What parameter of the Range.Find method specifies the data to search for.

    To find the first empty (or blank) cell in a column, set the What parameter to a zero-length string (“”).

    After:=ColumnRangeObject.Cells(ColumnRangeObject.Cells.Count)

    The After parameter of the Range.Find method specifies the cell after which the search begins.

    To find the first empty (or blank) cell in a column, set the After parameter to “ColumnRangeObject.Cells(ColumnRangeObject.Cells.Count)”. For these purposes:

    • “ColumnRangeObject” is a Range object representing the column whose first empty (or blank) cell you search for.
    • The Range.Cells property (Cells) returns a Range object representing all cells in the column whose first empty (or blank) cell you search for.
    • The Range.Item property returns a Range object representing the last cell in the column whose first empty (or blank) cell you search for. For these purposes, the RowIndex parameter of the Range.Item property is set to the value returned by the Range.Count property (Count).
    • The Range.Count property (Count) returns the number of cells in the Range object returned by the Range.Cells property (ColumnRangeObject.Cells).
    LookIn:=xlFormulas

    The LookIn parameter of the Range.Find method:

    • Specifies the type of data to search in.
    • Can take any of the built-in constants/values from the XlFindLookIn enumeration.

    To find the first empty (or blank) cell in a column, set the LookIn parameter to xlFormulas. xlFormulas refers to formulas.

    LookAt:=xlWhole

    The LookAt parameter of the Range.Find method:

    • Specifies against which of the following the data you are searching for is matched:
      • The entire/whole searched cell contents.
      • Any part of the searched cell contents.
    • The LookAt parameter can take any of the built-in constants/values from the XlLookAt enumeration.

    To find the first empty (or blank) cell in a column, set the LookAt parameter to xlWhole. xlWhole matches the data you are searching for against the entire/whole searched cell contents.

    SearchOrder:=xlByRows

    The SearchOrder parameter of the Range.Find method:

    • Specifies the order in which the applicable cell range (ColumnRangeObject) is searched:
      • By rows.
      • By columns.
    • Can take any of the built-in constants/values from the XlSearchOrder enumeration.

    To find the first empty (or blank) cell in a column, set the SearchOrder parameter to xlByRows. xlByRows searches by rows.

    SearchDirection:=xlNext

    The SearchDirection parameter of the Range.Find method:

    • Specifies the search direction:
      • Search for the previous match.
      • Search for the next match.
    • Can take any of the built-in constants/values from the XlSearchDirection enumeration.

    To find the first empty (or blank) cell in a column, set the SearchDirection parameter to xlNext. xlNext searches for the next match.

    Macro Example to Find First Empty (or Blank) Cell in Column

    The following macro (User-Defined Function) example does the following:

    1. Accepts one argument (MyColumn): The letter of the column (in the worksheet where the UDF is used) whose first empty (or blank) cell you search for.
    2. Finds the first empty (or blank) cell in the applicable column.
    3. Returns a string containing the address (as an A1-style relative reference) of the first empty (or blank) cell in the applicable column.
    Function FindFirstEmptyCellColumn(MyColumn As String) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 1 argument: MyColumn
            '(2) Finds the first empty (blank) cell in the column whose letter is passed as argument (MyColumn) in the worksheet where the UDF is used
            '(3) Returns the address (as an A1-style relative reference) of the first empty (blank) cell in the column whose letter is passed as argument (MyColumn) in the worksheet where the UDF is used
        With Application.Caller.Parent.Columns(MyColumn)
            FindFirstEmptyCellColumn = .Find(What:="", After:=.Cells(.Cells.Count), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext).Address(RowAbsolute:=False, ColumnAbsolute:=False)
        End With
    
    End Function
    

    Effects of Executing Macro Example to Find First Empty (or Blank) Cell in Column

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column I (cells I1 to I25) contains:
      • Data; and
      • A few empty cells (with light green interior/fill).
    • Cell A7 contains the letter of the column whose first empty (or blank) cell is sought (I).
    • Cell B7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an A1-style relative reference) of the first empty (or blank) cell in column I (MyColumn). This is cell I10.
    • Cell C7 displays the worksheet formula used in cell B7 (=FindFirstEmptyCellColumn(A7)). The letter of the column whose first empty (or blank) cell is sought is stored in cell A7 (A7).

    Example: Find first empty (or blank) cell in column with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #19. Excel VBA Find Next Empty (or Blank) Cell in Column

    VBA Code to Find Next Empty (or Blank) Cell in Column

    To find the next empty (or blank) cell in a column, use the following structure/template in the applicable procedure:

    If IsEmpty(RangeObjectSourceCell) Then
        RangeObjectSourceCell.ActionForNextEmptyCell
    ElseIf IsEmpty(RangeObjectSourceCell.Offset(1, 0)) Then
        RangeObjectSourceCell.Offset(1, 0).ActionForNextEmptyCell
    Else
        RangeObjectSourceCell.End(xlDown).Offset(1, 0).ActionForNextEmptyCell
    End If
    

    The following Sections describe the main elements in this structure.

    Lines #1, #3, #5 and #7: If IsEmpty(RangeObjectSourceCell) Then | ElseIf IsEmpty(RangeObjectSourceCell.Offset(1, 0)) Then | Else | End If

    If… Then | ElseIf… Then | Else | End If

    The If… Then… Else statement:

    • Conditionally executes a set of statements (lines #2, #4 or #6);
    • Depending on an expression’s value (IsEmpty(RangeObjectSourceCell) or IsEmpty(RangeObjectSourceCell.Offset(1, 0))).
    IsEmpty(RangeObjectSourceCell)

    The condition of an If… Then… Else statement is an expression evaluating to True or False. If the expression returns True, the applicable set of statements (line #2) is executed.

    In this expression:

    • As a general rule, the IsEmpty function returns a Boolean value (True or False) indicating whether a variable is initialized. You can (also) use the IsEmpty function to test whether a cell is empty (or blank).
    • RangeObjectSourceCell is a Range object representing the cell where the search (for the next empty or blank cell in the column) begins.
    • IsEmpty(RangeObjectSourceCell) returns True or False as follows:
      • True if the cell represented by RangeObjectSourceCell is empty (or blank).
      • False if the cell represented by RangeObjectSourceCell isn’t empty. A cell isn’t considered to be empty if, for example, it contains a worksheet formula returning a zero-length string (“”).
    IsEmpty(RangeObjectSourceCell.Offset(1, 0))

    The condition of an If… Then… Else statement is an expression evaluating to True or False. If the expression returns True, the applicable set of statements (line #4) is executed.

    In this expression:

    • As a general rule, the IsEmpty function returns a Boolean value (True or False) indicating whether a variable is initialized. You can (also) use the IsEmpty function to test whether a cell is empty (or blank).
    • RangeObjectSourceCell is a Range object representing the cell where the search (for the next empty or blank cell in the column) begins.
    • The Range.Offset property (Offset(1, 0)) returns a Range object representing a cell range at an offset from the source cell range. In this expression:
      • The source cell range is the cell where the search (for the next empty or blank cell in the column) begins (RangeObjectSourceCell).
      • The offset from the source cell range is as follows:
        • 1 row downwards, as specified by the RowOffset parameter of the Range.Offset property (1).
        • No column offsetting, as specified by the ColumnOffset parameter of the Range.Offset property (0).
    • IsEmpty(RangeObjectSourceCell.Offset(1, 0)) returns True or False as follows:
      • True if the cell represented by the Range object returned by the Range.Offset property is empty.
      • False if the cell represented by the Range object returned by the Range.Offset property isn’t empty. A cell isn’t considered to be empty if, for example, it contains a worksheet formula returning a zero-length string (“”).

    Line #2: RangeObjectSourceCell.ActionForNextEmptyCell

    Statement conditionally executed by the If… Then… Else statement if the applicable condition (IsEmpty(RangeObjectSourceCell)) returns True.

    RangeObjectSourceCell

    A Range object representing the cell where the search (for the next empty or blank cell in the column) begins.

    ActionForNextEmptyCell

    VBA construct (usually a property or method) working with the applicable cell (represented by RangeObjectSourceCell).

    Line #4: RangeObjectSourceCell.Offset(1, 0).ActionForNextEmptyCell

    Statement conditionally executed by the If… Then… Else statement if the applicable condition (IsEmpty(RangeObjectSourceCell.Offset(1, 0))) returns True.

    RangeObjectSourceCell

    A Range object representing the cell where the search (for the next empty or blank cell in the column) begins.

    Offset(1, 0)

    The Range.Offset property (Offset(1, 0)) returns a Range object representing a cell range at an offset from the source cell range. For these purposes:

    • The source cell range is the cell where the search (for the next empty or blank cell in the column) begins (RangeObjectSourceCell).
    • The offset from the source cell range is as follows:
      • 1 row downwards, as specified by the RowOffset parameter of the Range.Offset property (1).
      • No column offsetting, as specified by the ColumnOffset parameter of the Range.Offset property (0).
    ActionForNextEmptyCell

    VBA construct (usually a property or method) working with the applicable cell (returned by the Range.Offset property).

    Line #6: RangeObjectSourceCell.End(xlDown).Offset(1, 0).ActionForNextEmptyCell

    Statement conditionally executed by the If… Then… Else statement if no previous condition (in lines #1 or #3) returns True.

    RangeObjectSourceCell

    A Range object representing the cell where the search (for the next empty or blank cell in the column) begins.

    End(xlDown)

    The Range.End property returns a Range object representing the cell at the end of the region containing the source range. In other words: The Range.End property is the rough equivalent of using the “Ctrl + Arrow Key” or “End, Arrow Key” keyboard shortcuts.

    The Range.End property accepts one parameter: Direction. Direction:

    • Specifies the direction in which to move.
    • Can take the any of the built-in constants/values from the XlDirection enumeration.

    To find the next empty (or blank) cell in a column, set the Direction parameter to xlDown. xlDown:

    • Results in moving down, to the bottom of the data region.
    • Is the rough equivalent of the “Ctrl + Down Arrow” or “End, Down Arrow” keyboard shortcuts.
    Offset(1, 0)

    The Range.Offset property (Offset(1, 0)) returns a Range object representing a cell range at an offset from the source cell range. For these purposes:

    • The source cell range is the cell represented by the Range object returned by the Range.End property (End(xlDown)).
    • The offset from the source cell range is as follows:
      • 1 row downwards, as specified by the RowOffset parameter of the Range.Offset property (1).
      • No column offsetting, as specified by the ColumnOffset parameter of the Range.Offset property (0).
    ActionForNextEmptyCell

    VBA construct (usually a property or method) working with the applicable cell (returned by the Range.Offset property).

    Macro Example to Find Next Empty (or Blank) Cell in Column

    The following macro (User-Defined Function) example does the following:

    1. Accepts one argument (MySourceCell): The cell where the search (for the next empty or blank cell in the column) begins.
    2. Finds the next empty (or blank) cell in the applicable column after MySourceCell.
    3. Returns a string containing the address (as an R1C1-style absolute reference) of the next empty (or blank) cell in the applicable column.
    Function FindNextEmptyCellColumn(MySourceCell As Range) As String
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 1 argument: MySourceCell
            '(2) Finds the next empty/blank cell in the applicable column and after the cell passed as argument (MySourceCell)
            '(3) Returns the address (as an R1C1-style absolute reference) of the next empty/blank cell in the applicable column and after the cell passed as argument (MySourceCell)
        
        With MySourceCell(1)
            
            'If first cell in cell range passed as argument (MySourceCell) is empty, obtain/return that cell's address
            If IsEmpty(MySourceCell(1)) Then
                FindNextEmptyCellColumn = .Address(ReferenceStyle:=xlR1C1)
            
            'If cell below first cell in cell range passed as argument (MySourceCell) is empty, obtain/return that cell's address
            ElseIf IsEmpty(.Offset(1, 0)) Then
                FindNextEmptyCellColumn = .Offset(1, 0).Address(ReferenceStyle:=xlR1C1)
            
            'Otherwise:
                '(1) Find the next empty/blank cell in the applicable column and after the first cell in cell range passed as argument (MySourceCell)
                '(2) Obtain/return the applicable cell's address
            Else
                FindNextEmptyCellColumn = .End(xlDown).Offset(1, 0).Address(ReferenceStyle:=xlR1C1)
            End If
            
        End With
    
    End Function
    

    Effects of Executing Macro Example to Find Next Empty (or Blank) Cell in Column

    The following image illustrates the effects of using the macro (User-Defined Function) example. In this example:

    • Column A (cells A6 to A30) contains:
      • Data; and
      • A few empty cells.
    • Cell C7 contains the worksheet formula that works with the macro (User-Defined Function) example. This worksheet formula returns the address (as an R1C1-style absolute reference) of the next empty (or blank) cell in column A after cell A13 (MySourceCell). This cell R21C1 (or A21 as an A1-style relative reference).
    • Cell D7 displays the worksheet formula used in cell C7 (=FindNextEmptyCellColumn(A13)). The cell where the search (for the next empty or blank cell in the column) begins is A13 (A13).
    Example: Find next empty cell in column with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    #20. Excel VBA Find Value in Array

    VBA Code to Find Value in Array

    To find a numeric value in a one-dimensional array, use the following structure/template in the applicable procedure:

    Dim PositionOfValueInArray As Variant
    Dim LoopCounter As Long
    PositionOfValueInArray = OutputIfValueNotInArray
    For LoopCounter = LBound(SearchedArray) To UBound(SearchedArray)
        If SearchedArray(LoopCounter) = SearchedValue Then
            PositionOfValueInArray = LoopCounter
            Exit For
        End If
    Next LoopCounter
    

    The following Sections describe the main elements in this structure.

    Lines #1 and #2: Dim PositionOfValueInArray As Variant | Dim LoopCounter As Long

    The Dim statement:

    1. Declares variables.
    2. Allocates storage space.
    PositionOfValueInArray | LoopCounter

    The names of the variables declared with the Dim statement.

    • PositionOfValueInArray holds/represents:
      • The position of the searched numeric value in the array, if the searched numeric value is found in the array.
      • The default/fallback output/data, if the searched numeric value isn’t found in the array.
    • LoopCounter represents the loop counter used in the For… Next loop in lines #4 to #9.
    As Variant | As Long

    The data type of the variables declared with the Dim statement.

    • PositionOfValueInArray is of the Variant data type. The Variant data type can (generally) contain any type of data, except for fixed-length Strings.
    • LoopCounter is of the Long data type. The Long data type can contain integers between -2,147,483,648 and 2,147,483,647.

    Line #3: PositionOfValueInArray = OutputIfValueNotInArray

    PositionOfValueInArray

    Variable holding/representing:

    • The position of the searched numeric value in the array, if the searched numeric value is found in the array.
    • The default/fallback output/data, if the searched numeric value isn’t found in the array.
    =

    The assignment operator assigns the result returned by an expression (OutputIfValueNotInArray) to a variable (PositionOfValueInArray).

    OutputIfValueNotInArray

    Expression specifying the default/fallback output/data to be assigned to the PositionOfValueInArray variable if the searched numeric value isn’t found in the array.

    Lines #4 and #9: For LoopCounter = LBound(SearchedArray) To UBound(SearchedArray) | Next LoopCounter

    For… = … To … | Next…

    The For… Next statement repeats a series of statements a specific number of times.

    LoopCounter

    Variable holding/representing the loop counter.

    LBound(…) | UBound(…)

    The LBound/UBound functions return the lower/upper bound of an array’s dimension. The LBound/UBound functions accept two arguments:

    • ArrayName: The name of the array whose lower/upper bound you want to obtain.
    • Dimension:
      • An optional argument.
      • The dimension (of the applicable array) whose lower/upper bound you want to obtain.

    If you omit specifying the Dimension argument, the LBound/UBound functions return the lower/upper bound of the array’s first dimension.

    The initial/final values of LoopCounter are set to the following:

    • Initial value (Start) of LoopCounter: The output returned by the LBound function (LBound(SearchedArray)).
    • Final value (End) of LoopCounter: The output returned by the UBound function (UBound(SearchedArray)).
    SearchedArray

    The array you search in.

    SearchedArray is passed as the ArrayName argument of the LBound/UBound functions.

    Lines #5 and #8: If SearchedArray(LoopCounter) = SearchedValue Then | End If

    If… Then… End If

    The If… Then… Else statement:

    1. Conditionally executes a set of statements (lines #6 and #7);
    2. Depending on an expression’s value (SearchedArray(LoopCounter) = SearchedValue).
    SearchedArray(LoopCounter) = SearchedValue

    The condition of an If… Then… Else statement is an expression evaluating to True or False.

    • If the expression returns True, a set of statements (lines #6 and #7) is executed.
    • If the expression returns False:
      • No statements are executed.
      • Execution continues with the statement following End If (line #8).

    In this expression:

    • SearchedArray: The array you search in.
    • LoopCounter: Variable holding/representing the loop counter.
    • SearchedArray(LoopCounter): Array element whose index number is LoopCounter.
    • =: The equal to comparison operator returns True or False as follows:
      • True if both expressions (SearchedArray(LoopCounter) and SearchedValue) are equal.
      • False if the expressions (SearchedArray(LoopCounter) and SearchedValue) are not equal.
    • SearchedValue: Numeric value you search for in the array (SearchedArray).

    Line #6: PositionOfValueInArray = LoopCounter

    PositionOfValueInArray

    Variable holding/representing:

    • The position of the searched numeric value in the array, if the searched numeric value is found in the array.
    • The default/fallback output/data, if the searched numeric value isn’t found in the array.
    =

    The assignment operator assigns the result returned by an expression (LoopCounter) to a variable (PositionOfValueInArray).

    LoopCounter

    Variable holding/representing the loop counter.

    Line #7: Exit For

    The Exit For statement:

    • Exits a For… Next loop.
    • Transfers control to the statement following the Next statement (line #8).

    Macro Example to Find Value in Array

    The following macro (User-Defined Function) example does the following:

    1. Accepts two arguments:
      1. MyArray: The array you search in.
      2. MyValue: The numeric value you search for.
    2. Loops through each element in MyArray and tests whether the applicable element is equal to MyValue.
    3. Returns the following:
      1. If MyValue is not found in MyArray, the string “Value not found in array”.
      2. If MyValue is found in MyArray, the position/index number of MyValue in MyArray.
    Function FindValueInArray(MyArray As Variant, MyValue As Variant) As Variant
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This UDF:
            '(1) Accepts 2 arguments: MyArray and MyValue
            '(2) Loops through each element in the array (MyArray) and tests whether the applicable element is equal to the searched value (MyValue)
            '(3) Returns the following (as applicable):
                'If MyValue is not found in MyArray: The string "Value not found in array"
                'If MyValue is found in MyArray: The position (index number) of MyValue in MyArray
        
        'Declare variable to represent loop counter
        Dim iCounter As Long
    
        'Specify default/fallback value/string to be returned ("Value not found in array") if MyValue is not found in MyArray
        FindValueInArray = "Value not found in array"
    
        'Loop through each element in the array (MyArray)
        For iCounter = LBound(MyArray) To UBound(MyArray)
        
            'Test if the current array element is equal to MyValue
            If MyArray(iCounter) = MyValue Then
                
                'If the current array element is equal to MyValue:
                    '(1) Return the position (index number) of the current array element
                    '(2) Exit the For... Next loop
                FindValueInArray = iCounter
                Exit For
                
            End If
            
        Next iCounter
    
    End Function
    

    Effects of Executing Macro Example to Find Value in Array

    To illustrate the effects of using the macro (User-Defined Function) example, I use the following macro. The following macro does the following:

    1. Declare an array (MySearchedArray).
    2. Fill the array with values (0, 10, 20, …, 90).
    3. Call the FindValueInArray macro (User-Defined Function) example to find the number “50” in the array.
    4. Display a message box with the value/string returned by the FindValueInArray macro (User-Defined Function) example.
    Sub FindValueInArrayCaller()
        'Source: https://powerspreadsheets.com/
        'For further information: https://powerspreadsheets.com/excel-vba-find/
        
        'This procedure:
            '(1) Declares an array and fills it with values (0, 10, 20, ..., 90)
            '(2) Calls the FindValueInArray UDF to find the number "50" in the array
            '(3) Displays a message box with the value/string returned by the FindValueInArray UDF
        
        'Declare a zero-based array with 10 elements of the Long data type
        Dim MySearchedArray(0 To 9) As Long
        
        'Assign values to array elements
        MySearchedArray(0) = 0
        MySearchedArray(1) = 10
        MySearchedArray(2) = 20
        MySearchedArray(3) = 30
        MySearchedArray(4) = 40
        MySearchedArray(5) = 50
        MySearchedArray(6) = 60
        MySearchedArray(7) = 70
        MySearchedArray(8) = 80
        MySearchedArray(9) = 90
        
        'Do the following:
            '(1) Call the FindValueInArray UDF and search for the number "50" in MySearchedArray
            '(2) Display a message box with the value/string returned by the FindValueInArray UDF
        MsgBox FindValueInArray(MySearchedArray, 50)
        
    
    End Sub
    

    The following GIF illustrates the effects of using the macro above to call the macro (User-Defined Function) example.

    As expected, this results in Excel displaying a message box with the number 5. This is the position of the searched numeric value (50) in the array.

    Example: Find value in array with VBA macros

    Get immediate free access to the Excel VBA Find workbook example

    Learn More About Excel VBA Find

    Workbook Example Used in this Excel VBA Find Tutorial

    This VBA Find Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples above. You can get free access to this example workbook by clicking the button below.

    Get immediate free access to the Excel VBA Find workbook example

    The Power Spreadsheets Library

    The Books at The Power Spreadsheets Library are comprehensive and actionable guides for professionals who want to:

    • Automate Excel;
    • Save time for the things that really matter; and
    • Open new career opportunities.

    Learn more about The Power Spreadsheets Library here.

    This post will guide you how to insert character or text in middle of cells in Excel. How do I add text string or character to each cell of a column or range with a formula in Excel. How to add text to the beginning of all selected cells in Excel. How to add character after the first character of cells in Excel.

    Assuming that you have a list of data in range B1:B5 that contain string values and you want to add one character “E” after the first character of string in Cells. You can refer to the following two methods.

    Table of Contents

    • 1. Insert Character or Text to Cells with a Formula
    • 2. Insert Character or Text to Cells with VBA
    • 3. Video: Insert Character or Text to Cells
    • 4. Related Functions

    1. Insert Character or Text to Cells with a Formula

    To insert the character to cells in Excel, you can use a formula based on the LEFT function and the MID function. Like this:

    =LEFT(B1,1) & "E" & MID(B1,2,299)

    Type this formula into a blank cell, such as: Cell C1, and press Enter key. And then drag the AutoFill Handle down to other cells to apply this formula.

    insert text to cells1

    This formula will inert the character “E” after the first character of string in Cells. And if you want to insert the character or text string after the second or third or N position of the string in Cells, you just need to replace the number 1 in Left function and the number 2 in MID function as 2 and 3. Like below:

    =LEFT(B1,2) & "E" & MID(B1,3,299)

    insert text to cells2

    You can also use an Excel VBA Macro to insert one character or text after the first position of the text string in Cells. Just do the following steps:

    Step1: open your excel workbook and then click on “Visual Basic” command under DEVELOPER Tab, or just press “ALT+F11” shortcut.

    Get the position of the nth using excel vba1

    Step2: then the “Visual Basic Editor” window will appear.

    Step3: click “Insert” ->”Module” to create a new module.

    convert column number to letter3

    Step4: paste the below VBA code into the code window. Then clicking “Save” button.

    insert text to cells3

    Sub AddCharToCells()
        Dim cel As Range
        Dim curR As Range
        Set curR = Application.Selection
        Set curR = Application.InputBox("select one Range that you want to insert one 
        character", "add character to cells", curR.Address, Type: = 8)
        For Each cel In curR
            cel.Value = VBA.Left(cel.Value, 1) & "E" & VBA.Mid(cel.Value, 2, 
            VBA.Len(cel.Value) - 1)
        Next
    End Sub
    

    Step5: back to the current worksheet, then run the above excel macro. Click Run button.

    insert text to cells4

    Step6: select one Range that you want to insert one character.
    insert text to cells5

    Step7: lets see the result.

    insert text to cells6

    3. Video: Insert Character or Text to Cells

    This video will demonstrate how to insert character or text in middle of cells in Excel using both formulas and VBA code.

    • Excel MID function
      The Excel MID function returns a substring from a text string at the position that you specify.The syntax of the MID function is as below:= MID (text, start_num, num_chars)…
    • Excel LEFT function
      The Excel LEFT function returns a substring (a specified number of the characters) from a text string, starting from the leftmost character.The LEFT function is a build-in function in Microsoft Excel and it is categorized as a Text Function.The syntax of the LEFT function is as below:= LEFT(text,[num_chars])…

    “It is a capital mistake to theorize before one has data”- Sir Arthur Conan Doyle

    This post covers everything you need to know about using Cells and Ranges in VBA. You can read it from start to finish as it is laid out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.

    Topics covered include Offset property, reading values between cells, reading values to arrays and formatting cells.

    A Quick Guide to Ranges and Cells

    Function Takes Returns Example Gives

    Range

    cell address multiple cells .Range(«A1:A4») $A$1:$A$4
    Cells row, column one cell .Cells(1,5) $E$1
    Offset row, column multiple cells Range(«A1:A2»)
    .Offset(1,2)
    $C$2:$C$3
    Rows row(s) one or more rows .Rows(4)
    .Rows(«2:4»)
    $4:$4
    $2:$4
    Columns column(s) one or more columns .Columns(4)
    .Columns(«B:D»)
    $D:$D
    $B:$D

    Download the Code

     

    The Webinar

    If you are a member of the VBA Vault, then click on the image below to access the webinar and the associated source code.

    (Note: Website members have access to the full webinar archive.)

    vba ranges video

    Introduction

    This is the third post dealing with the three main elements of VBA. These three elements are the Workbooks, Worksheets and Ranges/Cells. Cells are by far the most important part of Excel. Almost everything you do in Excel starts and ends with Cells.

     
    Generally speaking, you do three main things with Cells

    1. Read from a cell.
    2. Write to a cell.
    3. Change the format of a cell.

     
    Excel has a number of methods for accessing cells such as Range, Cells and Offset.These can cause confusion as they do similar things and can lead to confusion

    In this post I will tackle each one, explain why you need it and when you should use it.

     
    Let’s start with the simplest method of accessing cells – using the Range property of the worksheet.

    Important Notes

    I have recently updated this article so that is uses Value2.

    You may be wondering what is the difference between Value, Value2 and the default:

    ' Value2
    Range("A1").Value2 = 56
    
    ' Value
    Range("A1").Value = 56
    
    ' Default uses value
    Range("A1") = 56
    

     
    Using Value may truncate number if the cell is formatted as currency. If you don’t use any property then the default is Value.

    It is better to use Value2 as it will always return the actual cell value(see this article from Charle Williams.)

    The Range Property

    The worksheet has a Range property which you can use to access cells in VBA. The Range property takes the same argument that most Excel Worksheet functions take e.g. “A1”, “A3:C6” etc.

    The following example shows you how to place a value in a cell using the Range property.

    ' https://excelmacromastery.com/
    Public Sub WriteToCell()
    
        ' Write number to cell A1 in sheet1 of this workbook
        ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 67
    
        ' Write text to cell A2 in sheet1 of this workbook
        ThisWorkbook.Worksheets("Sheet1").Range("A2").Value2 = "John Smith"
    
        ' Write date to cell A3 in sheet1 of this workbook
        ThisWorkbook.Worksheets("Sheet1").Range("A3").Value2 = #11/21/2017#
    
    End Sub
    

     
    As you can see Range is a member of the worksheet which in turn is a member of the Workbook. This follows the same hierarchy as in Excel so should be easy to understand. To do something with Range you must first specify the workbook and worksheet it belongs to.

    For the rest of this post I will use the code name to reference the worksheet.

    code name worksheet

     
     
    The following code shows the above example using the code name of the worksheet i.e. Sheet1 instead of ThisWorkbook.Worksheets(“Sheet1”).

    ' https://excelmacromastery.com/
    Public Sub UsingCodeName()
    
        ' Write number to cell A1 in sheet1 of this workbook
        Sheet1.Range("A1").Value2 = 67
    
        ' Write text to cell A2 in sheet1 of this workbook
        Sheet1.Range("A2").Value2 = "John Smith"
    
        ' Write date to cell A3 in sheet1 of this workbook
        Sheet1.Range("A3").Value2 = #11/21/2017#
    
    End Sub
    

    You can also write to multiple cells using the Range property

    ' https://excelmacromastery.com/
    Public Sub WriteToMulti()
    
        ' Write number to a range of cells
        Sheet1.Range("A1:A10").Value2 = 67
    
        ' Write text to multiple ranges of cells
        Sheet1.Range("B2:B5,B7:B9").Value2 = "John Smith"
    
    End Sub
    

     
    You can download working examples of all the code from this post from the top of this article.
     

    The Cells Property of the Worksheet

    The worksheet object has another property called Cells which is very similar to range. There are two differences

    1. Cells returns a range of one cell only.
    2. Cells takes row and column as arguments.

     
    The example below shows you how to write values to cells using both the Range and Cells property

    ' https://excelmacromastery.com/
    Public Sub UsingCells()
    
        ' Write to A1
        Sheet1.Range("A1").Value2 = 10
        Sheet1.Cells(1, 1).Value2  = 10
    
        ' Write to A10
        Sheet1.Range("A10").Value2 = 10
        Sheet1.Cells(10, 1).Value2  = 10
    
        ' Write to E1
        Sheet1.Range("E1").Value2 = 10
        Sheet1.Cells(1, 5).Value2  = 10
    
    End Sub
    

     
    You may be wondering when you should use Cells and when you should use Range. Using Range is useful for accessing the same cells each time the Macro runs.

    For example, if you were using a Macro to calculate a total and write it to cell A10 every time then Range would be suitable for this task.

    Using the Cells property is useful if you are accessing a cell based on a number that may vary. It is easier to explain this with an example.

     
    In the following code, we ask the user to specify the column number. Using Cells gives us the flexibility to use a variable number for the column.

    ' https://excelmacromastery.com/
    Public Sub WriteToColumn()
    
        Dim UserCol As Integer
        
        ' Get the column number from the user
        UserCol = Application.InputBox(" Please enter the column...", Type:=1)
        
        ' Write text to user selected column
        Sheet1.Cells(1, UserCol).Value2 = "John Smith"
    
    End Sub
    

     
    In the above example, we are using a number for the column rather than a letter.

    To use Range here would require us to convert these values to the letter/number  cell reference e.g. “C1”. Using the Cells property allows us to provide a row and a column number to access a cell.

    Sometimes you may want to return more than one cell using row and column numbers. The next section shows you how to do this.

    Using Cells and Range together

    As you have seen you can only access one cell using the Cells property. If you want to return a range of cells then you can use Cells with Ranges as follows

    ' https://excelmacromastery.com/
    Public Sub UsingCellsWithRange()
    
        With Sheet1
            ' Write 5 to Range A1:A10 using Cells property
            .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5
    
            ' Format Range B1:Z1 to be bold
            .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
    
        End With
    
    End Sub
    

     
    As you can see, you provide the start and end cell of the Range. Sometimes it can be tricky to see which range you are dealing with when the value are all numbers. Range has a property called Address which displays the letter/ number cell reference of any range. This can come in very handy when you are debugging or writing code for the first time.

     
    In the following example we print out the address of the ranges we are using:

    ' https://excelmacromastery.com/
    Public Sub ShowRangeAddress()
    
        ' Note: Using underscore allows you to split up lines of code
        With Sheet1
    
            ' Write 5 to Range A1:A10 using Cells property
            .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5
            Debug.Print "First address is : " _
                + .Range(.Cells(1, 1), .Cells(10, 1)).Address
    
            ' Format Range B1:Z1 to be bold
            .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True
            Debug.Print "Second address is : " _
                + .Range(.Cells(1, 2), .Cells(1, 26)).Address
    
        End With
    
    End Sub
    

     
    In the example I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)

     
    ImmediateWindow

     
    ImmediateSampeText

     
    You can download all the code for this post from the top of this article.
     

    The Offset Property of Range

    Range has a property called Offset. The term Offset refers to a count from the original position. It is used a lot in certain areas of programming. With the Offset property you can get a Range of cells the same size and a certain distance from the current range. The reason this is useful is that sometimes you may want to select a Range based on a certain condition. For example in the screenshot below there is a column for each day of the week. Given the day number(i.e. Monday=1, Tuesday=2 etc.) we need to write the value to the correct column.

     
    VBA Offset

     
    We will first attempt to do this without using Offset.

    ' https://excelmacromastery.com/
    ' This sub tests with different values
    Public Sub TestSelect()
    
        ' Monday
        SetValueSelect 1, 111.21
        ' Wednesday
        SetValueSelect 3, 456.99
        ' Friday
        SetValueSelect 5, 432.25
        ' Sunday
        SetValueSelect 7, 710.17
    
    End Sub
    
    ' Writes the value to a column based on the day
    Public Sub SetValueSelect(lDay As Long, lValue As Currency)
    
        Select Case lDay
            Case 1: Sheet1.Range("H3").Value2 = lValue
            Case 2: Sheet1.Range("I3").Value2 = lValue
            Case 3: Sheet1.Range("J3").Value2 = lValue
            Case 4: Sheet1.Range("K3").Value2 = lValue
            Case 5: Sheet1.Range("L3").Value2 = lValue
            Case 6: Sheet1.Range("M3").Value2 = lValue
            Case 7: Sheet1.Range("N3").Value2 = lValue
        End Select
    
    End Sub
    

     
    As you can see in the example, we need to add a line for each possible option. This is not an ideal situation. Using the Offset Property provides a much cleaner solution

    ' https://excelmacromastery.com/
    ' This sub tests with different values
    Public Sub TestOffset()
    
        DayOffSet 1, 111.01
        DayOffSet 3, 456.99
        DayOffSet 5, 432.25
        DayOffSet 7, 710.17
    
    End Sub
    
    Public Sub DayOffSet(lDay As Long, lValue As Currency)
    
        ' We use the day value with offset specify the correct column
        Sheet1.Range("G3").Offset(, lDay).Value2 = lValue
    
    End Sub
    

     
    As you can see this solution is much better. If the number of days in increased then we do not need to add any more code. For Offset to be useful there needs to be some kind of relationship between the positions of the cells. If the Day columns in the above example were random then we could not use Offset. We would have to use the first solution.

     
    One thing to keep in mind is that Offset retains the size of the range. So .Range(“A1:A3”).Offset(1,1) returns the range B2:B4. Below are some more examples of using Offset

    ' https://excelmacromastery.com/
    Public Sub UsingOffset()
    
        ' Write to B2 - no offset
        Sheet1.Range("B2").Offset().Value2 = "Cell B2"
    
        ' Write to C2 - 1 column to the right
        Sheet1.Range("B2").Offset(, 1).Value2 = "Cell C2"
    
        ' Write to B3 - 1 row down
        Sheet1.Range("B2").Offset(1).Value2 = "Cell B3"
    
        ' Write to C3 - 1 column right and 1 row down
        Sheet1.Range("B2").Offset(1, 1).Value2 = "Cell C3"
    
        ' Write to A1 - 1 column left and 1 row up
        Sheet1.Range("B2").Offset(-1, -1).Value2 = "Cell A1"
    
        ' Write to range E3:G13 - 1 column right and 1 row down
        Sheet1.Range("D2:F12").Offset(1, 1).Value2 = "Cells E3:G13"
    
    End Sub
    

    Using the Range CurrentRegion

    CurrentRegion returns a range of all the adjacent cells to the given range.

    In the screenshot below you can see the two current regions. I have added borders to make the current regions clear.

    VBA CurrentRegion

    A row or column of blank cells signifies the end of a current region.

    You can manually check the CurrentRegion in Excel by selecting a range and pressing Ctrl + Shift + *.

    If we take any range of cells within the border and apply CurrentRegion, we will get back the range of cells in the entire area.

    For example
    Range(“B3”).CurrentRegion will return the range B3:D14
    Range(“D14”).CurrentRegion will return the range B3:D14
    Range(“C8:C9”).CurrentRegion will return the range B3:D14
    and so on

    How to Use

    We get the CurrentRegion as follows

    ' Current region will return B3:D14 from above example
    Dim rg As Range
    Set rg = Sheet1.Range("B3").CurrentRegion
    

    Read Data Rows Only

    Read through the range from the second row i.e.skipping the header row

    ' Current region will return B3:D14 from above example
    Dim rg As Range
    Set rg = Sheet1.Range("B3").CurrentRegion
    
    ' Start at row 2 - row after header
    Dim i As Long
    For i = 2 To rg.Rows.Count
        ' current row, column 1 of range
        Debug.Print rg.Cells(i, 1).Value2
    Next i
    

    Remove Header

    Remove header row(i.e. first row) from the range. For example if range is A1:D4 this will return A2:D4

    ' Current region will return B3:D14 from above example
    Dim rg As Range
    Set rg = Sheet1.Range("B3").CurrentRegion
    
    ' Remove Header
    Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1)
    
    ' Start at row 1 as no header row
    Dim i As Long
    For i = 1 To rg.Rows.Count
        ' current row, column 1 of range
        Debug.Print rg.Cells(i, 1).Value2
    Next i
    

     

    Using Rows and Columns as Ranges

    If you want to do something with an entire Row or Column you can use the Rows or Columns property of the Worksheet. They both take one parameter which is the row or column number you wish to access

    ' https://excelmacromastery.com/
    Public Sub UseRowAndColumns()
    
        ' Set the font size of column B to 9
        Sheet1.Columns(2).Font.Size = 9
    
        ' Set the width of columns D to F
        Sheet1.Columns("D:F").ColumnWidth = 4
    
        ' Set the font size of row 5 to 18
        Sheet1.Rows(5).Font.Size = 18
    
    End Sub
    

    Using Range in place of Worksheet

    You can also use Cells, Rows and Columns as part of a Range rather than part of a Worksheet. You may have a specific need to do this but otherwise I would avoid the practice. It makes the code more complex. Simple code is your friend. It reduces the possibility of errors.

     
    The code below will set the second column of the range to bold. As the range has only two rows the entire column is considered B1:B2

    ' https://excelmacromastery.com/
    Public Sub UseColumnsInRange()
    
        ' This will set B1 and B2 to be bold
        Sheet1.Range("A1:C2").Columns(2).Font.Bold = True
    
    End Sub
    

     
    You can download all the code for this post from the top of this article.
     

    Reading Values from one Cell to another

    In most of the examples so far we have written values to a cell. We do this by placing the range on the left of the equals sign and the value to place in the cell on the right. To write data from one cell to another we do the same. The destination range goes on the left and the source range goes on the right.

     
    The following example shows you how to do this:

    ' https://excelmacromastery.com/
    Public Sub ReadValues()
    
        ' Place value from B1 in A1
        Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2
    
        ' Place value from B3 in sheet2 to cell A1
        Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2
    
        ' Place value from B1 in cells A1 to A5
        Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1").Value2
    
        ' You need to use the "Value" property to read multiple cells
        Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2
    
    End Sub
    

     
    As you can see from this example it is not possible to read from multiple cells. If you want to do this you can use the Copy function of Range with the Destination parameter

    ' https://excelmacromastery.com/
    Public Sub CopyValues()
    
        ' Store the copy range in a variable
        Dim rgCopy As Range
        Set rgCopy = Sheet1.Range("B1:B5")
    
        ' Use this to copy from more than one cell
        rgCopy.Copy Destination:=Sheet1.Range("A1:A5")
    
        ' You can paste to multiple destinations
        rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6")
    
    End Sub
    

     
    The Copy function copies everything including the format of the cells. It is the same result as manually copying and pasting a selection. You can see more about it in the Copying and Pasting Cells section.

    Using the Range.Resize Method

    When copying from one range to another using assignment(i.e. the equals sign), the destination range must be the same size as the source range.

    Using the Resize function allows us to resize a range to a given number of rows and columns.

    For example:
     

    ' https://excelmacromastery.com/
    Sub ResizeExamples()
     
        ' Prints A1
        Debug.Print Sheet1.Range("A1").Address
    
        ' Prints A1:A2
        Debug.Print Sheet1.Range("A1").Resize(2, 1).Address
    
        ' Prints A1:A5
        Debug.Print Sheet1.Range("A1").Resize(5, 1).Address
        
        ' Prints A1:D1
        Debug.Print Sheet1.Range("A1").Resize(1, 4).Address
        
        ' Prints A1:C3
        Debug.Print Sheet1.Range("A1").Resize(3, 3).Address
        
    End Sub
    

     
    When we want to resize our destination range we can simply use the source range size.

    In other words, we use the row and column count of the source range as the parameters for resizing:

    ' https://excelmacromastery.com/
    Sub Resize()
    
        Dim rgSrc As Range, rgDest As Range
        
        ' Get all the data in the current region
        Set rgSrc = Sheet1.Range("A1").CurrentRegion
    
          ' Get the range destination
        Set rgDest = Sheet2.Range("A1")
        Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count)
        
        rgDest.Value2 = rgSrc.Value2
    
    End Sub
    

     
    We can do the resize in one line if we prefer:

    ' https://excelmacromastery.com/
    Sub ResizeOneLine()
    
        Dim rgSrc As Range
        
        ' Get all the data in the current region
        Set rgSrc = Sheet1.Range("A1").CurrentRegion
        
        With rgSrc
            Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2
        End With
        
    End Sub
    

    Reading Values to variables

    We looked at how to read from one cell to another. You can also read from a cell to a variable. A variable is used to store values while a Macro is running. You normally do this when you want to manipulate the data before writing it somewhere. The following is a simple example using a variable. As you can see the value of the item to the right of the equals is written to the item to the left of the equals.

    ' https://excelmacromastery.com/
    Public Sub UseVariables()
    
        ' Create
        Dim number As Long
    
        ' Read number from cell
        number = Sheet1.Range("A1").Value2
    
        ' Add 1 to value
        number = number + 1
    
        ' Write new value to cell
        Sheet1.Range("A2").Value2 = number
    
    End Sub
    

     
    To read text to a variable you use a variable of type String:

    ' https://excelmacromastery.com/
    Public Sub UseVariableText()
    
        ' Declare a variable of type string
        Dim text As String
    
        ' Read value from cell
        text = Sheet1.Range("A1").Value2
    
        ' Write value to cell
        Sheet1.Range("A2").Value2 = text
    
    End Sub
    

     
    You can write a variable to a range of cells. You just specify the range on the left and the value will be written to all cells in the range.

    ' https://excelmacromastery.com/
    Public Sub VarToMulti()
    
        ' Read value from cell
        Sheet1.Range("A1:B10").Value2 = 66
    
    End Sub
    

     
    You cannot read from multiple cells to a variable. However you can read to an array which is a collection of variables. We will look at doing this in the next section.

    How to Copy and Paste Cells

    If you want to copy and paste a range of cells then you do not need to select them. This is a common error made by new VBA users.

    Note: We normally use Range.Copy when we want to copy formats, formulas, validation. If we want to copy values it is not the most efficient method.
    I have written a complete guide to copying data in Excel VBA here.

     
    You can simply copy a range of cells like this:

    Range("A1:B4").Copy Destination:=Range("C5")
    

     
    Using this method copies everything – values, formats, formulas and so on. If you want to copy individual items you can use the PasteSpecial property of range.

     
    It works like this

    Range("A1:B4").Copy
    Range("F3").PasteSpecial Paste:=xlPasteValues
    Range("F3").PasteSpecial Paste:=xlPasteFormats
    Range("F3").PasteSpecial Paste:=xlPasteFormulas
    

     
    The following table shows a full list of all the paste types

    Paste Type
    xlPasteAll
    xlPasteAllExceptBorders
    xlPasteAllMergingConditionalFormats
    xlPasteAllUsingSourceTheme
    xlPasteColumnWidths
    xlPasteComments
    xlPasteFormats
    xlPasteFormulas
    xlPasteFormulasAndNumberFormats
    xlPasteValidation
    xlPasteValues
    xlPasteValuesAndNumberFormats

    Reading a Range of Cells to an Array

    You can also copy values by assigning the value of one range to another.

    Range("A3:Z3").Value2 = Range("A1:Z1").Value2
    

     
    The value of  range in this example is considered to be a variant array. What this means is that you can easily read from a range of cells to an array. You can also write from an array to a range of cells. If you are not familiar with arrays you can check them out in this post.  

     
    The following code shows an example of using an array with a range:

    ' https://excelmacromastery.com/
    Public Sub ReadToArray()
    
        ' Create dynamic array
        Dim StudentMarks() As Variant
    
        ' Read 26 values into array from the first row
        StudentMarks = Range("A1:Z1").Value2
    
        ' Do something with array here
    
        ' Write the 26 values to the third row
        Range("A3:Z3").Value2 = StudentMarks
    
    End Sub
    

     
    Keep in mind that the array created by the read is a 2 dimensional array. This is because a spreadsheet stores values in two dimensions i.e. rows and columns

    Going through all the cells in a Range

    Sometimes you may want to go through each cell one at a time to check value.

     
    You can do this using a For Each loop shown in the following code

    ' https://excelmacromastery.com/
    Public Sub TraversingCells()
    
        ' Go through each cells in the range
        Dim rg As Range
        For Each rg In Sheet1.Range("A1:A10,A20")
            ' Print address of cells that are negative
            If rg.Value < 0 Then
                Debug.Print rg.Address + " is negative."
            End If
        Next
    
    End Sub
    
    

     
    You can also go through consecutive Cells using the Cells property and a standard For loop.

     
    The standard loop is more flexible about the order you use but it is slower than a For Each loop.

    ' https://excelmacromastery.com/
    Public Sub TraverseCells()
     
        ' Go through cells from A1 to A10
        Dim i As Long
        For i = 1 To 10
            ' Print address of cells that are negative
            If Range("A" & i).Value < 0 Then
                Debug.Print Range("A" & i).Address + " is negative."
            End If
        Next
     
        ' Go through cells in reverse i.e. from A10 to A1
        For i = 10 To 1 Step -1
            ' Print address of cells that are negative
            If Range("A" & i) < 0 Then
                Debug.Print Range("A" & i).Address + " is negative."
            End If
        Next
     
    End Sub
    

    Formatting Cells

    Sometimes you will need to format the cells the in spreadsheet. This is actually very straightforward. The following example shows you various formatting you can add to any range of cells

    ' https://excelmacromastery.com/
    Public Sub FormattingCells()
    
        With Sheet1
    
            ' Format the font
            .Range("A1").Font.Bold = True
            .Range("A1").Font.Underline = True
            .Range("A1").Font.Color = rgbNavy
    
            ' Set the number format to 2 decimal places
            .Range("B2").NumberFormat = "0.00"
            ' Set the number format to a date
            .Range("C2").NumberFormat = "dd/mm/yyyy"
            ' Set the number format to general
            .Range("C3").NumberFormat = "General"
            ' Set the number format to text
            .Range("C4").NumberFormat = "Text"
    
            ' Set the fill color of the cell
            .Range("B3").Interior.Color = rgbSandyBrown
    
            ' Format the borders
            .Range("B4").Borders.LineStyle = xlDash
            .Range("B4").Borders.Color = rgbBlueViolet
    
        End With
    
    End Sub
    

    Main Points

    The following is a summary of the main points

    1. Range returns a range of cells
    2. Cells returns one cells only
    3. You can read from one cell to another
    4. You can read from a range of cells to another range of cells.
    5. You can read values from cells to variables and vice versa.
    6. You can read values from ranges to arrays and vice versa
    7. You can use a For Each or For loop to run through every cell in a range.
    8. The properties Rows and Columns allow you to access a range of cells of these types

    What’s Next?

    Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

    Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

    (NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

    Понравилась статья? Поделить с друзьями:
  • Vba excel shapes group
  • Vba excel shape свойства
  • Vba excel shape no fill
  • Vba excel set sheet
  • Vba excel set font