I am trying to copy and paste the format and formulas of a "masterrow" to a range in a loop. The loop also fetches data from another workbook, which therefore is the ActiveWorkbook during the loop.
I am thinking this "ActiveWorkbook" issue is what causes the problem, but I need help for the solution. I have supplied the loop function below. I hope you can help me.
Sub Worksheet_UpdateAllItemCostData()
Dim material As Variant
Dim fndEntry As Range
Dim wb1 As Workbook, wb2 As Workbook
Dim lr As Long, I As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb1 = ActiveWorkbook
lr = wb1.Sheets("Sagsnr.").Cells(Rows.Count, "C").End(xlUp).Row
If lr < 21 Then
Exit Sub
End If
Workbooks.Open Filename:="G:\Backoffice\Tilbudsteam\Kostdatabase\Matcost.xls", ReadOnly:=True
Set wb2 = ActiveWorkbook
For I = 21 To lr
wb1.Sheets("Sagsnr.").Rows("1:1").Select
selection.Copy
wb1.Sheets("Sagsnr.").Rows(I).Select
selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=True, Transpose:=False
selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
selection.EntireRow.Hidden = False
material = wb1.Sheets("Sagsnr.").Range("C" & I).Value
Set fndEntry = wb2.Sheets("Matcost").Range("D:D").Find(What:=material)
If Not fndEntry Is Nothing Then
wb1.Sheets("Sagsnr.").Range("B" & I).Value = wb2.Sheets("Matcost").Range("H" & fndEntry.Row).Value 'Product group
wb1.Sheets("Sagsnr.").Range("E" & I).Value = wb2.Sheets("Matcost").Range("Q" & fndEntry.Row).Value 'Available Stock
End If
Set fndEntry = wb2.Sheets("Matcost").Range("C:C").Find(What:=material)
If Not fndEntry Is Nothing Then
wb1.Sheets("Sagsnr.").Range("B" & I).Value = wb2.Sheets("Matcost").Range("H" & fndEntry.Row).Value 'Product group
wb1.Sheets("Sagsnr.").Range("E" & I).Value = wb2.Sheets("Matcost").Range("Q" & fndEntry.Row).Value 'Available Stock
End If
Next I
wb2.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub