This tutorial shows how to return the address of a first cell in a specific range using an Excel formula or VBA
Example: Return address of first cell in a range
METHOD 1. Return address of first cell in a range using Excel formula
EXCEL
This formula uses the Excel ADDRESS, ROW and COLUMN functions with the range from which you want to return the address of the first cell inserted as the reference in the ROW and COLUMN functions. |
METHOD 1. Return address of first cell in a range using VBA
VBA
Sub Address_of_first_cell_in_range()
‘declare variables
Dim ws As Worksheet
Dim rng As Range
Set ws = Worksheets(«Analysis»)
Set rng = ws.Range(«B5:C10»)
‘return the address of the first cell in a specified range
ws.Range(«E5») = rng(1).Address
End Sub
Explanation about how to return address of first cell in a range
EXPLANATION
EXPLANATION
This tutorial shows how to return an address of a first cell in a range through the use of an Excel formula or VBA.
The Excel formula uses the ADDRESS, ROW and COLUMN functions to return the address of the first cell in the specified range, whilst the VBA method uses only the Address function.
FORMULA
=ADDRESS(ROW(range),COLUMN(range))
ARGUMENTS
range: The range from which to return the address of the first cell.
Related Topic | Description | Related Topic and Description |
---|---|---|
Return address of a specific cell | How to return the address of a specific cell using Excel and VBA | |
Return address of active cell | How to return the address of an active cell using Excel and VBA |
Related Functions | Description | Related Functions and Description |
---|---|---|
ADDRESS Function | The Excel ADDRESS function returns a cell reference as a string, based on a row and column number | |
ROW Function | The Excel ROW function returns the first row number of the selected reference | |
COLUMN Function | The Excel COLUMN function returns the first column number of the selected reference |
When selecting a range in Excel manually, the first cell, or starting cell, of the selection has a different appearance. It does not have a gray layer over it like the rest of the cells in the selection.
I want to know the following: Is it possible to determine what the starting cell of a selection is using VBA
?
If this is possible it would go into the Private Sub Worksheet_SelectionChange(ByVal Target As Range)
asked Dec 14, 2017 at 11:21
SilentRevolutionSilentRevolution
1,4951 gold badge16 silver badges31 bronze badges
Selection.Address
will contain the total selected range — from top left to bottom right.
ActiveCell.Address
will have the cell that was the ‘start’ of the selection.
You can just refer to these in the event handler:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Debug.Print Selection.Address
Debug.Print ActiveCell.Address
End Sub
answered Dec 14, 2017 at 11:26
Robin MackenzieRobin Mackenzie
18.1k7 gold badges41 silver badges54 bronze badges
3
The first used or non-blank cell in an Excel worksheet can be found with the Range.Find method in VBA.
In this case, we will use the Range.Find method to start in the last cell in the worksheet, and set the SearchDirection
parameter to xlNext
. This then starts the search in the first cell in the worksheet (A1) and looks through each row until a non-blank cell is found.
We set the After
parameter to Cells(Rows.Count, Columns.Count)
to reference the last cell in the sheet. This will find the last cell with the Rows.Count and Columns.count properties, regardless of how many rows and columns are in the sheet.
The LookIn
parameter can be set to xlFormulas
to find any cell that contains a formula, even if the formula returns a blank. Set the LookIn
parameter to xlValues
to only search the values or results of formulas.
Here is the macro code you can copy/paste to your own Excel file.
Sub Find_First_Used_Cell()
'Finds the first non-blank cell in a worksheet.
Dim rFound As Range
On Error Resume Next
Set rFound = Cells.Find(What:="*", _
After:=Cells(Rows.Count, Columns.Count), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
On Error GoTo 0
If rFound Is Nothing Then
MsgBox "All cells are blank."
Else
MsgBox "First Cell: " & rFound.Address
End If
End Sub
I have an entire video series and article on how to find the LAST used or non-blank cell on a sheet with VBA.
Please leave a comment below with any questions.
In this Article
- Ranges and Cells in VBA
- Cell Address
- Range of Cells
- Writing to Cells
- Reading from Cells
- Non Contiguous Cells
- Intersection of Cells
- Offset from a Cell or Range
- Setting Reference to a Range
- Resize a Range
- OFFSET vs Resize
- All Cells in Sheet
- UsedRange
- CurrentRegion
- Range Properties
- Last Cell in Sheet
- Last Used Row Number in a Column
- Last Used Column Number in a Row
- Cell Properties
- Copy and Paste
- AutoFit Contents
- More Range Examples
- For Each
- Sort
- Find
- Range Address
- Range to Array
- Array to Range
- Sum Range
- Count Range
Ranges and Cells in VBA
Excel spreadsheets store data in Cells. Cells are arranged into Rows and Columns. Each cell can be identified by the intersection point of it’s row and column (Exs. B3 or R3C2).
An Excel Range refers to one or more cells (ex. A3:B4)
Cell Address
A1 Notation
In A1 notation, a cell is referred to by it’s column letter (from A to XFD) followed by it’s row number(from 1 to 1,048,576). This is called a cell address.
In VBA you can refer to any cell using the Range Object.
' Refer to cell B4 on the currently active sheet
MsgBox Range("B4")
' Refer to cell B4 on the sheet named 'Data'
MsgBox Worksheets("Data").Range("B4")
' Refer to cell B4 on the sheet named 'Data' in another OPEN workbook
' named 'My Data'
MsgBox Workbooks("My Data").Worksheets("Data").Range("B4")
R1C1 Notation
In R1C1 Notation a cell is referred by R followed by Row Number then letter ‘C’ followed by the Column Number. eg B4 in R1C1 notation will be referred by R4C2. In VBA you use the Cells Object to use R1C1 notation:
' Refer to cell R[6]C[4] i.e D6
Cells(6, 4) = "D6"
Range of Cells
A1 Notation
To refer to a more than one cell use a “:” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:
Range("A1:D10")
R1C1 Notation
To refer to a more than one cell use a “,” between the starting cell address and last cell address. The following will refer to all the cells from A1 to D10:
Range(Cells(1, 1), Cells(10, 4))
Writing to Cells
To write values to a cell or contiguous group of cells, simple refer to the range, put an = sign and then write the value to be stored:
' Store F5 in cell with Address F6
Range("F6") = "F6"
' Store E6 in cell with Address R[6]C[5] i.e E6
Cells(6, 5) = "E6"
' Store A1:D10 in the range A1:D10
Range("A1:D10") = "A1:D10"
' or
Range(Cells(1, 1), Cells(10, 4)) = "A1:D10"
Reading from Cells
To read values from cells, simple refer to the variable to store the values, put an = sign and then refer to the range to be read:
Dim val1
Dim val2
' Read from cell F6
val1 = Range("F6")
' Read from cell E6
val2 = Cells(6, 5)
MsgBox val1
Msgbox val2
Note: To store values from a range of cells, you need to use an Array instead of a simple variable.
Non Contiguous Cells
To refer to non contiguous cells use a comma between the cell addresses:
' Store 10 in cells A1, A3, and A5
Range("A1,A3,A5") = 10
' Store 10 in cells A1:A3 and D1:D3)
Range("A1:A3, D1:D3") = 10
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Intersection of Cells
To refer to non contiguous cells use a space between the cell addresses:
' Store 'Col D' in D1:D10
' which is Common between A1:D10 and D1:F10
Range("A1:D10 D1:G10") = "Col D"
Offset from a Cell or Range
Using the Offset function, you can move the reference from a given Range (cell or group of cells) by the specified number_of_rows, and number_of_columns.
Offset Syntax
Range.Offset(number_of_rows, number_of_columns)
Offset from a cell
' OFFSET from a cell A1
' Refer to cell itself
' Move 0 rows and 0 columns
Range("A1").Offset(0, 0) = "A1"
' Move 1 rows and 0 columns
Range("A1").Offset(1, 0) = "A2"
' Move 0 rows and 1 columns
Range("A1").Offset(0, 1) = "B1"
' Move 1 rows and 1 columns
Range("A1").Offset(1, 1) = "B2"
' Move 10 rows and 5 columns
Range("A1").Offset(10, 5) = "F11"
Offset from a Range
' Move Reference to Range A1:D4 by 4 rows and 4 columns
' New Reference is E5:H8
Range("A1:D4").Offset(4,4) = "E5:H8"
Setting Reference to a Range
To assign a range to a range variable: declare a variable of type Range then use the Set command to set it to a range. Please note that you must use the SET command as RANGE is an object:
' Declare a Range variable
Dim myRange as Range
' Set the variable to the range A1:D4
Set myRange = Range("A1:D4")
' Prints $A$1:$D$4
MsgBox myRange.Address
VBA Programming | Code Generator does work for you!
Resize a Range
Resize method of Range object changes the dimension of the reference range:
Dim myRange As Range
' Range to Resize
Set myRange = Range("A1:F4")
' Prints $A$1:$E$10
Debug.Print myRange.Resize(10, 5).Address
Top-left cell of the Resized range is same as the top-left cell of the original range
Resize Syntax
Range.Resize(number_of_rows, number_of_columns)
OFFSET vs Resize
Offset does not change the dimensions of the range but moves it by the specified number of rows and columns. Resize does not change the position of the original range but changes the dimensions to the specified number of rows and columns.
All Cells in Sheet
The Cells object refers to all the cells in the sheet (1048576 rows and 16384 columns).
' Clear All Cells in Worksheets
Cells.Clear
UsedRange
UsedRange property gives you the rectangular range from the top-left cell used cell to the right-bottom used cell of the active sheet.
Dim ws As Worksheet
Set ws = ActiveSheet
' $B$2:$L$14 if L2 is the first cell with any value
' and L14 is the last cell with any value on the
' active sheet
Debug.Print ws.UsedRange.Address
CurrentRegion
CurrentRegion property gives you the contiguous rectangular range from the top-left cell to the right-bottom used cell containing the referenced cell/range.
Dim myRange As Range
Set myRange = Range("D4:F6")
' Prints $B$2:$L$14
' If there is a filled path from D4:F16 to B2 AND L14
Debug.Print myRange.CurrentRegion.Address
' You can refer to a single starting cell also
Set myRange = Range("D4") ' Prints $B$2:$L$14
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Range Properties
You can get Address, row/column number of a cell, and number of rows/columns in a range as given below:
Dim myRange As Range
Set myRange = Range("A1:F10")
' Prints $A$1:$F$10
Debug.Print myRange.Address
Set myRange = Range("F10")
' Prints 10 for Row 10
Debug.Print myRange.Row
' Prints 6 for Column F
Debug.Print myRange.Column
Set myRange = Range("E1:F5")
' Prints 5 for number of Rows in range
Debug.Print myRange.Rows.Count
' Prints 2 for number of Columns in range
Debug.Print myRange.Columns.Count
Last Cell in Sheet
You can use Rows.Count and Columns.Count properties with Cells object to get the last cell on the sheet:
' Print the last row number
' Prints 1048576
Debug.Print "Rows in the sheet: " & Rows.Count
' Print the last column number
' Prints 16384
Debug.Print "Columns in the sheet: " & Columns.Count
' Print the address of the last cell
' Prints $XFD$1048576
Debug.Print "Address of Last Cell in the sheet: " & Cells(Rows.Count, Columns.Count)
Last Used Row Number in a Column
END property takes you the last cell in the range, and End(xlUp) takes you up to the first used cell from that cell.
Dim lastRow As Long
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Last Used Column Number in a Row
Dim lastCol As Long
lastCol = Cells(1, Columns.Count).End(xlToLeft).Column
END property takes you the last cell in the range, and End(xlToLeft) takes you left to the first used cell from that cell.
You can also use xlDown and xlToRight properties to navigate to the first bottom or right used cells of the current cell.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Cell Properties
Common Properties
Here is code to display commonly used Cell Properties
Dim cell As Range
Set cell = Range("A1")
cell.Activate
Debug.Print cell.Address
' Print $A$1
Debug.Print cell.Value
' Prints 456
' Address
Debug.Print cell.Formula
' Prints =SUM(C2:C3)
' Comment
Debug.Print cell.Comment.Text
' Style
Debug.Print cell.Style
' Cell Format
Debug.Print cell.DisplayFormat.NumberFormat
Cell Font
Cell.Font object contains properties of the Cell Font:
Dim cell As Range
Set cell = Range("A1")
' Regular, Italic, Bold, and Bold Italic
cell.Font.FontStyle = "Bold Italic"
' Same as
cell.Font.Bold = True
cell.Font.Italic = True
' Set font to Courier
cell.Font.FontStyle = "Courier"
' Set Font Color
cell.Font.Color = vbBlue
' or
cell.Font.Color = RGB(255, 0, 0)
' Set Font Size
cell.Font.Size = 20
Copy and Paste
Paste All
Ranges/Cells can be copied and pasted from one location to another. The following code copies all the properties of source range to destination range (equivalent to CTRL-C and CTRL-V)
'Simple Copy
Range("A1:D20").Copy
Worksheets("Sheet2").Range("B10").Paste
'or
' Copy from Current Sheet to sheet named 'Sheet2'
Range("A1:D20").Copy destination:=Worksheets("Sheet2").Range("B10")
Paste Special
Selected properties of the source range can be copied to the destination by using PASTESPECIAL option:
' Paste the range as Values only
Range("A1:D20").Copy
Worksheets("Sheet2").Range("B10").PasteSpecial Paste:=xlPasteValues
Here are the possible options for the Paste option:
' Paste Special Types
xlPasteAll
xlPasteAllExceptBorders
xlPasteAllMergingConditionalFormats
xlPasteAllUsingSourceTheme
xlPasteColumnWidths
xlPasteComments
xlPasteFormats
xlPasteFormulas
xlPasteFormulasAndNumberFormats
xlPasteValidation
xlPasteValues
xlPasteValuesAndNumberFormats
AutoFit Contents
Size of rows and columns can be changed to fit the contents using AutoFit:
' Change size of rows 1 to 5 to fit contents
Rows("1:5").AutoFit
' Change size of Columns A to B to fit contents
Columns("A:B").AutoFit
More Range Examples
It is recommended that you use Macro Recorder while performing the required action through the GUI. It will help you understand the various options available and how to use them.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
For Each
It is easy to loop through a range using For Each construct as show below:
For Each cell In Range("A1:B100")
' Do something with the cell
Next cell
At each iteration of the loop one cell in the range is assigned to the variable cell and statements in the For loop are executed for that cell. Loop exits when all the cells are processed.
Sort
Sort is a method of Range object. You can sort a range by specifying options for sorting to Range.Sort. The code below will sort the columns A:C based on key in cell C2. Sort Order can be xlAscending or xlDescending. Header:= xlYes should be used if first row is the header row.
Columns("A:C").Sort key1:=Range("C2"), _
order1:=xlAscending, Header:=xlYes
Find
Find is also a method of Range Object. It find the first cell having content matching the search criteria and returns the cell as a Range object. It return Nothing if there is no match.
Use FindNext method (or FindPrevious) to find next(previous) occurrence.
Following code will change the font to “Arial Black” for all cells in the range which start with “John”:
For Each c In Range("A1:A100")
If c Like "John*" Then
c.Font.Name = "Arial Black"
End If
Next c
Following code will replace all occurrences of “To Test” to “Passed” in the range specified:
With Range("a1:a500")
Set c = .Find("To Test", LookIn:=xlValues)
If Not c Is Nothing Then
firstaddress = c.Address
Do
c.Value = "Passed"
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstaddress
End If
End With
It is important to note that you must specify a range to use FindNext. Also you must provide a stopping condition otherwise the loop will execute forever. Normally address of the first cell which is found is stored in a variable and loop is stopped when you reach that cell again. You must also check for the case when nothing is found to stop the loop.
Range Address
Use Range.Address to get the address in A1 Style
MsgBox Range("A1:D10").Address
' or
Debug.Print Range("A1:D10").Address
Use xlReferenceStyle (default is xlA1) to get addres in R1C1 style
MsgBox Range("A1:D10").Address(ReferenceStyle:=xlR1C1)
' or
Debug.Print Range("A1:D10").Address(ReferenceStyle:=xlR1C1)
This is useful when you deal with ranges stored in variables and want to process for certain addresses only.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Range to Array
It is faster and easier to transfer a range to an array and then process the values. You should declare the array as Variant to avoid calculating the size required to populate the range in the array. Array’s dimensions are set to match number of values in the range.
Dim DirArray As Variant
' Store the values in the range to the Array
DirArray = Range("a1:a5").Value
' Loop to process the values
For Each c In DirArray
Debug.Print c
Next
Array to Range
After processing you can write the Array back to a Range. To write the Array in the example above to a Range you must specify a Range whose size matches the number of elements in the Array.
Use the code below to write the Array to the range D1:D5:
Range("D1:D5").Value = DirArray
Range("D1:H1").Value = Application.Transpose(DirArray)
Please note that you must Transpose the Array if you write it to a row.
Sum Range
SumOfRange = Application.WorksheetFunction.Sum(Range("A1:A10"))
Debug.Print SumOfRange
You can use many functions available in Excel in your VBA code by specifying Application.WorkSheetFunction. before the Function Name as in the example above.
Count Range
' Count Number of Cells with Numbers in the Range
CountOfCells = Application.WorksheetFunction.Count(Range("A1:A10"))
Debug.Print CountOfCells
' Count Number of Non Blank Cells in the Range
CountOfNonBlankCells = Application.WorksheetFunction.CountA(Range("A1:A10"))
Debug.Print CountOfNonBlankCells
Written by: Vinamra Chandra
Manipulating ranges and cells is one of the most common actions in VBA. You can use the following to either learn from or just to copy and paste into your own code.
Referencing ranges & cells from the worksheet
'Reference range by address Workbooks("WorkbookName.xlsx").Worksheets("SheetName").Range("A1:D4").[Other properties and actions] 'Reference cells by row and column - Cells(Row,Column) Workbooks("WorkbookName.xlsx").Worksheets("SheetName").Cells(1, 1).[Other properties and actions] 'Reference ranges by a defined name Workbooks("WorkbookName.xlsx").Worksheets("SheetName").Range("RangeName").[Other properties and actions]
Assigning a range to a variable
'Assigning a range to a variable Dim Rng As Range Set Rng = Workbooks("WorkbookName.xlsx").Worksheets("SheetName").Range("A1:D4") 'Assigning a cell to a variable Dim Rng As Range Set Rng = Workbooks("WorkbookName.xlsx").Worksheets("SheetName").Cells(1, 1)
Selecting ranges and cells
'Select range by address Range("A1:D4").Select 'Select cells by row and column - Cells(Row,Column) Cells(1, 1).Select 'Select ranges by a defined name Range("RangeName").Select
Changing the value of a range or cell
'Change value of a range by address Range("A1:D4").Value = "Text here" 'Change value cells by row and column - Cells(Row,Column) Cells(1, 1).Value = 30
Setting the value of a variable based on the value of a cell
'Setting a variable based on a cell value Dim CellValue As Integer CellValue = Cells(1, 1).Value
Counting cells, rows and columns
'Count cells in a range Dim CellsInRange As Long CellsInRange = Range("A1:D4").Cells.Count 'Count rows in a range Dim RowsInRange As Long RowsInRange = Range("A1:D4").Rows.Count 'Count columns in a range Dim ColumnsInRange As Long ColumnsInRange = Range("A1:D4").Columns.Count
Looping through cells, rows and columns in a range
'Loop through action for each cell in a range Dim Rng As Range Dim CellsInRng As Range Set Rng = Range("A1:D4") For Each CellsInRange In Rng 'Carry out an action Next CellsInRange 'Loop through action for each row in a range Dim Rng As Range Dim CellsInRng As Range Set Rng = Range("A1:D4") For Each CellsInRange In Rng.Rows 'Carry out an action Next CellsInRange 'Loop through action for each column in a range Dim Rng As Range Dim CellsInRng As Range Set Rng = Range("A1:D4") For Each CellsInRange In Rng.Columns 'Carry out an action Next CellsInRange
Inserting rows, columns, ranges and cells
'Inserting Columns Columns("B:B").Insert 'Inserting Rows Rows("2:3").Insert 'Inserting a range of cells (shift cells to the right) Range("A1:D4").Insert Shift:=xlToRight 'Inserting a range of cells (shift cells to down) Range("A1:D4").Insert Shift:=xlDown
Deleting rows, columns, ranges and cells
'Deleting columns Columns("B:B").Delete 'Deleting rows Rows("3:4").Delete 'Delete a range of cells (shift cells to the right) Range("A1:D4").Delete Shift:=xlToLeft 'Delete a range of cells (shift cells to the down) Range("A1:D4").Delete Shift:=xlU
Copy and pasting
'Copy and paste everyting Range("A1:D4").Copy Range("H7").Paste 'Copy and paste values only Range("A1:D4").Copy Range("H7").PasteSpecial Paste:=xlPasteValues 'Copy and paste formats only Range("A1:D4").Copy Range("H7").PasteSpecial Paste:=xlPasteFormats
Copying and paste without using the clipboard
'Copy everyting Range("A1:D4").Copy Destination:=Range("H7") 'Copy values only Range("H7:K10").Value = Range("A1:D4").Value
Finding the last cell in a row or column
'Last used cell in one row Dim LastRow As Long LastRow = Workbooks("WorkbookName.xlsx").Worksheets("SheetName").Cells(Rows.Count, "A").End(xlUp).Row 'Last used cell in one column Dim LastCol As Integer LastCol = Workbooks("WorkbookName.xlsx").Worksheets("SheetName").Cells(1, Columns.Count).End(xlToLeft).Column
Finding the first cell in a range
'Find the row of first cell of a range Dim FirstRow As Long Dim Rng As Range Set Rng = Range("A1:D4") FirstRow = Rng.Row 'Find the column of first cell of a range Dim FirstColumn As Long Dim Rng As Range Set Rng = Range("A1:D4") FirstColumn = Rng.Column
Finding the row and column of the active cell
'Find the row of the active cell ActiveCell.Row 'Find the columns of the active cell ActiveCell.Column 'Find the address of the active cells ActiveCell.Address
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts: