title: Issue with looping through sheets in excel files and save as csv files
body: <p>I am writing a function that iterates through files in a folder. In each file, iterate through the sheets and save them as CSV files. I tested them without going through the sheets and it works fine. However, when I loop through the sheets, it keeps looping through the files. I ran the debug and found that when it is at the end of the last file, it goes back to the first file. I cannot find what was wrong. Here is my code:</p>
  
  <pre><code>Sub morningstar_VBA()
  'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
  'SOURCE: www.TheSpreadsheetGuru.com
  
  Dim wb As Workbook
  Dim myPath As String
  Dim myFile As String
  Dim myExtension As String
  Dim filename As String
  Dim path_to_save As String
  Dim FldrPicker As FileDialog
  Dim w As Long
  
  'Retrieve Target Folder Path From User
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
  
      With FldrPicker
        .Title = "Select A Target Folder"
        .AllowMultiSelect = False
          If .Show &lt;&gt; -1 Then GoTo NextCode
          myPath = .SelectedItems(1) &amp; "\"
      End With
  
  'In Case of Cancel
  NextCode:
    myPath = myPath
    If myPath = "" Then GoTo ResetSettings
  
  'Target File Extension (must include wildcard "*")
    myExtension = "*.xlsx*"
  
  'Target Path with Ending Extention
    myFile = Dir(myPath &amp; myExtension)
  
  'Loop through each Excel file in folder
    Do While myFile &lt;&gt; ""
      'Set variable equal to opened workbook
      Set wb = Workbooks.Open(filename:=myPath &amp; myFile)
  
      'Ensure Workbook has opened before moving on to next line of code
      For w = 1 To Worksheets.Count
          With Worksheets(w).Copy
              'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
              With ActiveWorkbook
                  filename = .Worksheets(1).Name
                  path_to_save = "E:\Morningstar_download\test\" &amp; filename
                  .SaveAs filename:=path_to_save, FileFormat:=xlCSV
                  DoEvents
                  .Close savechanges:=False
              End With
          End With
      Next w
  
      wb.Close savechanges:=True
  
      'Ensure Workbook has closed before moving on to next line of code
      DoEvents
  
      'Get next file name
      myFile = Dir
    Loop
  
  'Message Box when tasks are completed
    MsgBox "Task Complete!"
  
  ResetSettings:
    'Reset Macro Optimization Settings
      Application.EnableEvents = True
      Application.Calculation = xlCalculationAutomatic
      Application.ScreenUpdating = True
  
  End Sub
  </code></pre>