My code works from Module but does not work when linked to button. Please assist to resolve this error

Viewed 25

Sub Parent_Name()

'Formula to update Parent Name from column 1

Dim ws As Worksheet

Set ws = ThisWorkbook.Sheets("DB")

Sheets("DB").Select
        
last_row = Cells(Rows.Count, 1).End(xlUp).Row

Range("Y2").Select
ActiveCell.Formula = "=VLOOKUP(X2,'ML DB'!C:G,5,0)"

ActiveCell.AutoFill Destination:=Range(ActiveCell.Address & ":Y" & last_row)


Columns("Y:Y").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        
'Replace #N/A with ##
        
Columns("Y:Y").Select
Selection.Replace What:="#N/A", Replacement:="##", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Range("Y1").Select

Sheets("DB").Select

last_row = Cells(Rows.Count, 1).End(xlUp).Row

For iRow = 2 To last_row

    If Range("Y" & iRow).Value = "##" Then

ERROR OCCURES ON THIS LINE WHEN CLICKED VIA BUTTON (Run Time Error 1004, Application-defined or object-defined error)

ws.Range("Y" & iRow).Formula = Replace(Range("Y" & iRow), "##", "=VLOOKUP(X" & iRow & ",'ML DB'!D:G,4,0")
    

End If

Next iRow


Columns("Y:Y").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
        
'Replace #N/A with ##
        
Columns("Y:Y").Select
Selection.Replace What:="#N/A", Replacement:="##", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2

Range("Y1").Select

End Sub

1 Answers

Maybe try adding a few more & ?

ws.Range("Y" & iRow).Formula = Replace(Range("Y" & iRow     &        ), "##", "=VLOOKUP(X" & iRow & ",'ML DB'!D:G,4,0")
Related