Q:

Error 5 using Dir - Macro to copy a sheet from another workbook, using sheetname

I've been stucked on this today... 
I have a folder with several .xlsx files called "Files to modify"
Each of them has its first sheet named specificaly like "test1" for example.
I have another folder with other .xlsx files called "Old file to insert"
Each of these is called specifically like this : "old test1.xlsx", old test2, etc...
I want my macro to go through the first folder and files and copy the first sheet of the corresponding old .xlsx in the other folder.
The code is far from working but the main issue is that I get an error 5 on the Dir line and I think that it is because I use dir two times (the ProcessFiles macro works fine in another case where I do not need to use Dir in the DoWork sub).
Any help is welcomed, as you can guess I'm a beginner.
Here is my code
Sub ProcessFiles()

Dim FileName, Pathname As String
Dim wb As Workbook

Pathname = ActiveWorkbook.Path & "\Files to modify\"
FileName = Dir(Pathname & "*.xlsx", vbNormal)

Do While FileName <> ""

Set wb = Workbooks.Open(FileName:=Pathname & FileName, Local:=True)
DoWork wb
wb.Close True

Set wb = Nothing
FileName = Dir 'Error 5 is here

Loop

End Sub

Sub DoWork(wb As Workbook)
Dim FileName As String

FileName = Dir(ActiveWorkbook.Path & "\Old file to insert\" & "old " & ActiveSheet.Name & ".xlsx")

If FileName = "" Then
MsgBox "File does not exist"
Else
Set wb2 = Application.Workbooks.Open(FileName)
wb2.Sheets(1).Copy After:=wb.Sheets(1)

End If
End Sub

A:

As you expected, using Dir simultaneously at two different places is looking for trouble. 
In the sub DoWork you use just to check the existence of the file. You dont need to use it for this, you can directly try to open the Workbook and check if the opening succeeds..
Sub DoWork(wb As Workbook)
    Dim FileName As String
    ' Dont use Dir here
    Filename = ActiveWorkbook.Path & "\Old file to insert\" & "old " & ActiveSheet.Name & ".xlsx"  

    'Try to open the file if it exists, otherwise handle the error
    On Error Resume Next
    Set wb2 = Application.Workbooks.Open(Filename)
    If Err.Number <> 0 Then
        MsgBox "File does not exist or could not open"
    Else
          ' Now the file is open, continue work with it
          wb2.Sheets(1).Copy After:=wb.Sheets(1)
    End If
End Sub

