Search code examples
excelvbaoffset

Issue to offset lastrow


I have a problem to offset from the previous row my last row. Indeed I try to run my code below, I have the error message which appears

compile error: invalid qualifier…

The problem apparently comes from my variable lastRow4 = lastRow3.Offset(-1, 0)

When I remove this line of my code and I replaced in my VBA code the penultimate line Range("A3:F" & lastRow4).Select by Range("A3:F" & lastRow3).Select, my code works but the selection selects my range until lastrow (in my code, it is lastRow3) and it is not what I want.

If someone knows the solution how to fix the issue in order that my variable lastRow4 does not return me any error message, that would be great.

Many thanks in advance. Xavi

Sub gdfgdhgf()


Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer, lastRow3 As Integer, lastRow4 As Integer
Dim currentRowValue As String

sourceCol = 5 'column F has a value of 5
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row 'for every row, find the first blank cell and select it
For currentRow = 1 To rowCount
    currentRowValue = Cells(currentRow, sourceCol).Value
    If IsEmpty(currentRowValue) Or currentRowValue = "" Then
        lastRow3 = currentRow
    End If
Next
lastRow4 = lastRow3.Offset(-1, 0)
Range("A3:F" & lastRow4).Select

End Sub

Solution

  • The below is not the code. it is an example. modify and try:

    Option Explicit
    
    Sub test()
    
        Dim LastRow As Long
    
        With ThisWorkbook.Worksheets("Sheet1")
    
            LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row '<- Get the last row of column A sheet1
    
            'In order to refer to line before Lastrow you can use:
    
            .Range ("A" & LastRow - 1)
    
        End With
    
    End Sub