0
votes

I would like to loop through all excel workbooks in a folder and write the string "Test" in Cell A1 of every sheet of every workbook. The following code results in 'Subscript out of Range(Error 9)'. When I ran the code line by line it turned out the Error is caused by the line:
Workbooks(FName).Close Savechanges:=True
Dir("C\...") stored in FName returns just the file name so the error can't be because of giving the full path name to Workboooks(...).Close which seems often to be the reason for the error.
On top of that this code really opens the workbook instead of just writing into it. I don't want it to open visually.

Sub multWB()

Dim FName As String
Dim wb As Workbook
Dim sht As Worksheet
Dim directory As String

directory = "C:\Users\...\Desktop\multipleWorkbooks\"
FName = Dir("C:\Users\...\Desktop\multipleWorkbooks\*.xls*")

Do While FName <> ""


            Set wb = Workbooks.Open(directory & FName)
                   For Each sht In wb.Worksheets
                    sht.Cells(1, 1) = "Test"
                   Next
            FName = Dir

            Workbooks(FName).Close Savechanges:=True 'causes error


Loop
     Set wb = Nothing

End Sub
3
Try just doing Workbooks(FName).Close True - dwirony
@dwirony I tried that, but error is still there - Alias

3 Answers

2
votes

You already have a reference to the workbook with wb. Just use that reference!

wb.Close SaveChanges:=True

Anything else is dereferencing objects for no reason.

1
votes

You are retrieving the name of the next workbook before closing the current open one. Switch the order those two lines of code:

        Workbooks(FName).Close Savechanges:=True 
        FName = Dir()
0
votes

This: FName = Dir is missing the folder name. Change it to this:

FName = directory & Dir()