Home » excel » vba – Excel Not Finding Last Row Correctly

vba – Excel Not Finding Last Row Correctly

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to find the last row in a sheet as part of my macro. One step before this one copies large amounts of data to Worksheet 4. When I get to this step, excel wrongly identifies the last row as some random row in my worksheet. I’ve tried .Find and countless other methods, and nothing seems to work.

Sub Step19MatchStrike()

ActiveWorkbook.Save

Dim ws As Worksheet
Set ws = Worksheets(4)

Dim LastRowColumnA As Long

LastRowColumnA = ws.Cells(Rows.Count, 1).End(xlUp).Row
ws.Range("AA1").Value = "Strike Determination"
ws.Range("AA2").FormulaArray = "=IF((MATCH(E2,INDEX(Sheet3,(MATCH(A2,INDEX(Sheet3,,1),0)),5),0))>0,""To Keep"",""To Delete"")"
ws.Range("AA2").Copy ws.Range("AA3:AA" & LastRowColumnA)
ws.Columns(27).Value = ws.Columns(27).Value


End Sub
How to&Answers:

This code will do what you want

Sub Step19MatchStrike()
    Dim ws As Worksheet

    '~~> Change as applicable
    Set ws = Sheet1

    Dim lRow As Long

    With ws
        '~~> Find the last row in col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("AA1").Value = "Strike Determination"

        '~~> Fill the formula in one go
        .Range("AA2:AA" & lRow).FormulaArray = YOURFORMULA
        .Columns(27).Value = .Columns(27).Value
    End With
End Sub

I am just curious about Sheet3 in your formula. That doesn’t look right

"=IF((MATCH(E2,INDEX(Sheet3,(MATCH(A2,INDEX(Sheet3,,1),0)),5),0))>0,""To Keep"",""To Delete"")"

Edit

Using Autofill

Sub Step19MatchStrike()
    Dim ws As Worksheet

    '~~> Change as applicable
    Set ws = Sheet1

    Dim lRow As Long

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("AA1").Value = "Strike Determination"
        .Range("AA2").FormulaArray = "=IF((MATCH(E2,INDEX(Sheet3,(MATCH(A2,INDEX(Sheet3,,1),0)),5),0))>0,""To Keep"",""To Delete"")"
        .Range("AA2").AutoFill Destination:=.Range("AA2:AA" & lRow), Type:=xlFillDefault
    End With
End Sub

Answer:

How to avoid the usage of worksheet index.

Option Explicit

Sub test()

    Dim ws As Worksheet
    Dim LastRow As Long

    With ThisWorkbook
        'Refer to the worksheet using CodeName (the name appears in the VBA editor)
        Set ws = ws1
        'Refer to the worksheet using Name (the name appears in the Excel sheet)
        Set ws = .Worksheets("Sheet1")
    End With

    'Create as With Statement to avoid sheet repetition
    With ws
        'Find the last row
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

End Sub