I've been spending quite some time trying to get this sub to work but either my excel freezes or I get an error.
The error I usually get is Run-time error '1004': Application-defined or object-defined error --> on the 'set rng = ...' line
My problem:
I'm trying to get my sub to loop through a workbook that is preferably set as the ActiveWorkbook, instead of a set workbook, as it will be inside another loop that will loop through workbooks in a folder. I then want it to loop through the rows in workbook x and copy certain values from different columns shown by the different Cell.Offset(0,x). It then would need to paste these values to a master workbook denoted as y in the sub, in different columns shown by Range("A" & roww), Range("B" & roww), etc.
My code is here:
Sub transferingDataToMaster()
Dim x As Workbook, y As Workbook, rng As Range, Cell As Variant, roww As Long
'## Open both workbooks first:
Set x = Workbooks.Open("/Users/esrom/Desktop/P4H/Test/Jan_19_2.xlsm")
Set y = Workbooks.Open("/Users/esrom/Desktop/P4H/Test/Master_Test.xlsm")
Set rng = x.Sheets("Sheet1").Range(Range("G2"), Range("G2").End(xlDown))
For Each Cell In rng.Cells
roww = Cell.Row + 2
'Now, transfer values from x to y:
y.Sheets("Sheet1").Range("A" & roww).Value = Cell.Value
y.Sheets("Sheet1").Range("B" & roww).Value = Cell.Offset(0, 6).Value
y.Sheets("Sheet1").Range("C" & roww).Value = Cell.Offset(0, 7).Value
y.Sheets("Sheet1").Range("D" & roww).Value = Cell.Offset(0, 8).Value
y.Sheets("Sheet1").Range("E" & roww).Value = Cell.Offset(0, 10).Value
y.Sheets("Sheet1").Range("F" & roww).Value = Cell.Offset(0, 11).Value
Next
End Sub
I've tried looking at other questions but they don't seem to be applicable to mine and I can manage to get it to work for set values but not variables.
Would anyone be able to help me find the issue and correct the code please? Thanks in advance :)
x
andy
workbooks you've opened are actually open. So the testIf x Is Nothing Then Exit Sub
will work, or perform your own handling of that condition. – PeterTSet rng = x.Sheets("Sheet1").Range(x.Sheets("Sheet1").Range("G2"), x.Sheets("Sheet1").Range("G2").End(xlDown))
– BruceWayne