Deke
Deke

Reputation: 495

Excel Lastrow autofill issue with vba

I'm having an issue with my code to autofill some using VBA in Excel. I keep getting the error "AutoFill method of range class failed" but I'm not sure what is wrong with the code. it looks okay to me but maybe I'm missing something? The code is as follows:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
    Cancel As Boolean)


A = MsgBox("Do you really want to save the workbook?", vbYesNo)
If A = vbNo Then Cancel = True

Dim lrow As Long
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A" & lastrow)
Range("A1:A" & lastrow).Select

'Range("D1").Select
'Selection.AutoFill Destination:=Range("D1:D" & lastrow)
'Range("D1:D" & lastrow).Select
'Range("H1").Select
'Selection.AutoFill Destination:=Range("H1:H" & lastrow)
'Range("H1:H" & lastrow).Select
'Range("L1").Select
'Selection.AutoFill Destination:=Range("L1:L" & lastrow)
'Range("L1:L" & lastrow).Select
End Sub

Any help in the right direction would be greatly appreciated. (Note I am just trying to fix Column A I figure if I can get that working the rest will fall into line). Thanks!!! -D

Upvotes: 2

Views: 530

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149315

Is this what you are trying?

Option Explicit

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim Ret As Variant

    Ret = MsgBox("Do you really want to save the workbook?", vbYesNo)

    If Ret = vbNo Then
        Cancel = True
    Else
        '~~> Make these changes only if user wants to save the workbook
        Dim lrow As Long
        Dim ws As Worksheet

        Set ws = ThisWorkbook.Sheets(1)

        With ws
            '~~> If Col B has data then find the last row in Col B
            lrow = .Range("B" & .Rows.Count).End(xlUp).Row

            .Range("A1:A" & lrow).Formula = .Range("A1").Formula
        End With
    End If
End Sub

Upvotes: 2

Related Questions