ThisWorkbook.Path

Viewed 50
Sub a()

    Dim copy_range As Variant
  
    Application.Workbooks.Open Filename:=Dir(ThisWorkbook.Path & "/* (2).csv")
    copy_range = Sheets(1).Range("A1:C288").Value
    ActiveWorkbook.Close
    
    Sheets(2).Range("A1:C288") = copy_range
    
   
      
End Sub

In this part Dir(ThisWorkbook.Path & "/* (2).csv")

It says the file doesn't exist.

The current folder contains (2) to (19).csv . The full name of the file name is 20222022(2).csv 20222022(3).csv ~ 20222022(19).csv no see.

2 Answers

You don't need the DIR and you slash is the wrong way round, the following should work:

Application.Workbooks.Open Filename:=ActiveWorkbook.Path & "\*(2).csv"

Dir() only returns the file name, not the full path, so if the current directory isn't ThisWorkbook.Path it won't find the file.

Sub a()

    Dim copy_range As Variant, f, fldr As String, wb As Workbook

    fldr = ThisWorkbook.Path & "\"
    f = Dir(fldr & "* (2).csv", vbNormal)

    If Len(f) > 0 Then
        Set wb = Workbooks.Open(fldr & f)
        copy_range = wb.Sheets(1).Range("A1:C288").Value
        wb.Close
        ThisWorkbook.Sheets(2).Range("A1:C288") = copy_range
    Else
        MsgBox "No file found!"
    End If

End Sub
Related