Find last used cell in Excel VBA

When working with Excel VBA, it is common to need to find the last used cell in a range. This is useful for a variety of purposes, such as dynamically resizing arrays or performing calculations on a specific range of data.

Understanding the Problem

One way to find the last used cell in a range is to use the End method. In your code example, you are using Range("E4:E48").End(xlDown).Row to find the last used cell in column E between rows 4 and 48. However, you are experiencing issues when there is only a single value present in a cell.

Explanation

The reason you are getting the wrong output when there is a single value in a cell is because the End(xlDown) method is designed to find the last used cell by continuously moving down until it encounters an empty cell. When there is only a single value in a cell, the cell is not considered empty, so the End(xlDown) method will not stop at that cell.

Solution: Using End(xlUp)

To overcome this issue, you can use the End(xlUp) method instead. This method finds the last used cell by moving up from the bottom of the range until it encounters the first non-empty cell.


                Dim LastRow As Long
                LastRow = Range("E4:E48").End(xlUp).Row
                Debug.Print LastRow
            

This code snippet will correctly find the last used cell in the range E4:E48, regardless of whether there is a single value or multiple values present in the cells.

Alternative Solution: Using Find method

Another way to find the last used cell is by using the Find method, which allows you to search for a specific value or condition within a range.


                Dim LastCell As Range
                Set LastCell = Range("E4:E48").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
                Dim LastRow As Long
                LastRow = LastCell.Row
                Debug.Print LastRow
            

In this code snippet, the Find method is used to search for the last non-empty cell in the range E4:E48. The "*" argument is used as the search criteria, which matches any non-empty cell. The SearchOrder:=xlByRows and SearchDirection:=xlPrevious arguments ensure that the search is performed from the bottom of the range.

Conclusion

When working with Excel VBA, it is important to correctly find the last used cell in a range in order to perform accurate calculations or data manipulation. By using either the End(xlUp) method or the Find method, you can ensure that you are finding the last used cell regardless of whether there is a single value or multiple values present in the cells.