excelvbaexcel-formulaworksheet-functionworksheet

Autofill formulas for multiple worksheets with data from one worksheet


I am using this code for Worksheet A for autofilling Columns S & T regarding the length of column A:

Sub AutoFill()

Dim rc As Long

rc = Range("A" & Rows.Count).End(xlUp).Row
Range("S2:T2").AutoFill Range("S2:T" & rc)

End Sub

My problem is in Worksheet B. I have Column A to E with formula in A2:E2. I want to extend the formulas in Worksheet B, but only for the length of Column A in Worksheet A. I want one macro to do all these manipulations.

I tried this:

Sub AutoFill()

Dim rc As Long

rc = Range("A" & Rows.Count).End(xlUp).Row
Range("S2:T2").AutoFill Range("S2:T" & rc)
rc = Range("A" & Rows.Count).End(xlUp).Row
Range("WorksheetB!A2:WorksheetB!E2").AutoFill Range("WorksheetB!A2:WorksheetB!E" & rc)
 
End Sub

but it does not work.


Solution

  • Found a way to solve the issue:

    Sub AutoFill()
    
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim sh3 As Worksheet
    Dim sh4 As Worksheet
    Dim sh5 As Worksheet
    Dim rc As Long
    'Dim wkb As Workbook
    
    'Set wkb = Workbooks("Ontario-NewRecurrentCustomersV2") '-> best to call workbooks by name, as opposed to "ActiveWorkbook", also best to set it to object
    
    With ActiveWorkbook
    
        Set sh1 = .Sheets("CleanDataWeek")
        Set sh2 = .Sheets("CleanDataWeek(P-1)")
        Set sh3 = .Sheets("CalculatedDataWeek")
        Set sh4 = .Sheets("CalculatedDataWeek(P-1)")
        Set sh5 = .Sheets("RawData")
    
        rc = sh5.Range("A" & Rows.Count).End(xlUp).Row
        sh5.Range("S2:T2").AutoFill sh5.Range("S2:T" & rc)
    
        rc = sh5.Range("A" & Rows.Count).End(xlUp).Row
        sh1.Range("A2:E2").AutoFill sh1.Range("A2:E" & rc)
    
        rc = sh5.Range("A" & Rows.Count).End(xlUp).Row
        sh2.Range("A2:E2").AutoFill sh2.Range("A2:E" & rc)
    
        rc = sh5.Range("A" & Rows.Count).End(xlUp).Row
        sh3.Range("A2:F2").AutoFill sh3.Range("A2:F" & rc)
    
        rc = sh5.Range("A" & Rows.Count).End(xlUp).Row
        sh4.Range("A2:F2").AutoFill sh4.Range("A2:F" & rc)
    
    End With
    
    End Sub