33 - Excel VBA Code to Get Last Row or Column | How to find last row & column |

Опубликовано: 04 Октябрь 2024
на канале: ExcelSteps
49
3

33 - Excel VBA Code to Get Last Row or Column | How to find last row & column | #excelsteps

Download Link:
https://drive.google.com/drive/folder...


To find the last row or column in Excel using VBA, you can use various methods. Here are a few examples:

To find the last used row in a specific column:
```vba
Sub FindLastRow()
Dim lastRow As Long

' Specify the column you want to check (e.g., column A)
lastRow = Cells(Rows.Count, "A").End(xlUp).Row

' Display the last used row
MsgBox "The last used row in column A is " & lastRow
End Sub
```

In the above code, the `Cells(Rows.Count, "A")` expression selects the last cell in column A, and the `End(xlUp)` method navigates upwards from the last cell until it finds the last used cell. The `Row` property returns the row number of the last used cell.

To find the last used column in a specific row:
```vba
Sub FindLastColumn()
Dim lastColumn As Long

' Specify the row you want to check (e.g., row 1)
lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column

' Display the last used column
MsgBox "The last used column in row 1 is " & lastColumn
End Sub
```

In the code above, the `Cells(1, Columns.Count)` expression selects the last cell in row 1, and the `End(xlToLeft)` method navigates towards the left from the last cell until it finds the last used cell. The `Column` property returns the column number of the last used cell.

To find the last used row and column in the entire worksheet:
```vba
Sub FindLastRowAndColumn()
Dim lastRow As Long
Dim lastColumn As Long

' Find the last used row
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

' Find the last used column
lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column

' Display the last used row and column
MsgBox "Last used row: " & lastRow & vbNewLine & "Last used column: " & lastColumn
End Sub
```

This code combines the previous two examples to find the last used row and column in the entire worksheet.

You can modify these examples to fit your specific requirements, such as changing the column or row you want to check.