0

I am trying to create a macro that loops through all the non-txt files in a folder, open them, copy a selection from the opened file, and then paste it to a specific sheet in the file with the macro (depending on which file is being copied). I've got the first two parts working, but I'm not able to get the copy part to work. It keeps copying the file that should be the paste file. Any idea what I'm doing wrong?

Private Sub CommandButton1_Click()

Dim Path As String
Dim File As String
Dim PasteFile As String
Dim Month As String
Dim FY As String

Month = "feb"
FY = "18"
PasteFile = ThisWorkbook.Name

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Path = "[file path]"
file = Dir(Path)
Do While file <> "*.txt" Or file <> ""

    If file = "[file name]" & Month & FY & ".xlsx" Then
    Workbooks.Open Path & file
    Workbooks(file).Worksheets("Sheet1").Activate
    Range(Cells(1, 1), Cells(5, 5)).Copy
    Workbooks(myFile).Worksheets("Sheet1").Activate
    Cells(10, 3).PasteSpecial xlPasteValues

    End If
File = Dir()
Loop
End Sub
Community
  • 1
  • 1
tjm02c
  • 17
  • 7

1 Answers1

0

Avoid using .Activate and .Select

How to Avoid the Select Method in VBA & Why

Private Sub CommandButton1_Click()

Dim Path As String
Dim File As String
Dim PasteFile As String
Dim Month As String
Dim FY As String

Month = "feb"
FY = "18"
PasteFile = ThisWorkbook.Name

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Path = "[file path]"
File = Dir(Path)
Do While File <> "*.txt" Or File <> ""

    If File = "[file name]" & Month & FY & ".xlsx" Then

    Workbooks.Open Path & File

    With Workbooks(File).Worksheets("Sheet1")
    .Range(.Cells(1, 1), .Cells(5, 5)).Copy
    End With

    With Workbooks(myFile).Worksheets("Sheet1")
    .Cells(10, 3).PasteSpecial xlPasteValues
    End With

    End If

File = Dir()
Loop

End Sub
warner_sc
  • 848
  • 6
  • 13