Sometimes, You may need to find and select the first blank cell or last blank cell in a column, these macros can help you.
Find and Select the First Blank Cell in Column A
Sub Macro1()
Dim ws As Worksheet
Set ws = ActiveSheet
For Each cell In ws.Columns(1).Cells
If IsEmpty(cell) = True Then cell.Select: Exit For
Next cell
End Sub
or
Sub Macro2()
Dim ws As Worksheet
Set ws = ActiveSheet
For Each cell In ws.Columns(1).Cells
If Len(cell) = 0 Then cell.Select: Exit For
Next cell
End Sub
First blank cell: before selection
First blank cell: after selection
Find and Select the Last Blank Cell in Column A
Sub Macro3()
'Step 1: Declare Your Variables.
Dim LastRow As Long
'Step 2: Capture the last used row number.
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
'Step 3: Select the next row down
Cells(LastRow, 1).Offset(1, 0).Select
End Sub
or
Sub Macro4()
'Step 1: Declare Your Variables.
Dim LastBlankRow As Long
'Step 2: Capture the last used row number.
LastBlankRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
'Step 3: Select the next row down
Cells(LastBlankRow, 1).Select
End Sub
Note: Some of the most common ways of finding last row which are highly unreliable and hence should never be used:
UsedRange
xlDown
CountA
Why we use Rows.Count not 65536?
This question is a classic scenario where the code will fail because the Rows.Count
returns 65536
for Excel 2003 and earlier and 1048576
for Excel 2007 and later. The above fact that Excel 2007+ has 1048576
rows also emphasizes on the fact that we should always declare the variable which will hold the row value as Long
instead of Integer
else you will get an Overflow
error.
How to use it
To use this macro, you can copy and paste it into a standard module:
- Activate the Visual Basic Editor by pressing ALT F11.
- Right-click the project/workbook name in the Project window.
- Choose Insert -> Module.
- Type or paste the code in the newly created module.
Hi,
The macro works for column A. I want to repeat this process but for columns b.c.d.e,etc
The reason is that I am copying data from my invoice to a sheet to store my data of my invoice.
Can you help, please?
Hi,
How to paste the copied first cell into blank cells in the same column.
How can I include more then one of these in a single VBA?
Thanks Rob