Home » excel » vba – Multiple Excel workbooks and 1004 run-time error

vba – Multiple Excel workbooks and 1004 run-time error

Posted by: admin May 14, 2020 Leave a comment

Questions:

Bumped into run-time error 1004 at line “Set wbForm1Original = Workbooks.Open…” Would really appreciate some advice. This routine is to duplicate an original workbook and name the copy of the workbook based on some content in a data workbook, then copy the content of a row in the data workbook into this duplicated workbook. (Do the same for each row in the data workbook: duplicate, name, copy content)

Sub createForm()

Dim dirPath As String
Dim filePath As String
Dim file As String
Dim companyName As String
Dim n As Integer
Dim i As Integer
Dim wbVendor As Workbook
Dim wbForm1Original As Workbook
Dim wbForm1Company As Workbook

Set wbVendor = ThisWorkbook
dirPath = CurDir()
n = 5

For i = 2 To (n + 1)

    companyName = wbVendor.Worksheets("Sheet1").Cells(i, 1).Value

    file = "177_609 i_" & companyName & ".xlsx"
    filePath = dirPath & "\" & file

    Set wbForm1Original = Workbooks.Open("C:\Users\user1\Documents. Finance\Vendors7_609 i.xls")

    wbForm1Original.SaveCopyAs filePath
    Set wbForm1Company = Workbooks.Open(filePath)

    Workbooks("Vendor.xlsm").Worksheets("Sheet1").Range("A" & CStr(i)).Copy _
        Workbooks(file).Worksheets("Sheet1").Range("I13")
    Workbooks("Vendor.xlsm").Worksheets("Sheet1").Range("B" & CStr(i)).Copy _
        Workbooks(file).Worksheets("Sheet1").Range("I14")
    Workbooks("Vendor.xlsm").Worksheets("Sheet1").Range("C" & CStr(i)).Copy _
        Workbooks(file).Worksheets("Sheet1").Range("I15")
    Workbooks("Vendor.xlsm").Worksheets("Sheet1").Range("D" & CStr(i)).Copy _
        Workbooks(file).Worksheets("Sheet1").Range("E16")
    Workbooks("Vendor.xlsm").Worksheets("Sheet1").Range("E" & CStr(i)).Copy _
        Workbooks(file).Worksheets("Sheet1").Range("J16")
    Workbooks("Vendor.xlsm").Worksheets("Sheet1").Range("F" & CStr(i)).Copy _
        Workbooks(file).Worksheets("Sheet1").Range("M16")

Next i
End Sub
How to&Answers:

You are opening the workbook in a loop without closing it. Thus, it does not like it. Either close the workbook, before openning it again or put the openning outside the loop, like this:

Set wbForm1Original = Workbooks.Open("C:\.... Finance\Vendors7_609 i.xls")
wbForm1Original.SaveCopyAs filePath
Set wbForm1Company = Workbooks.Open(filePath)

For i = 2 To (n + 1)
'further code...