-1

My Aim:

This procedure is meant to loop through excel files in a specified folder and preform a sub (cleanDataAndTransfer), which is meant to clean the data in the files being looped through and then paste it in to a new sheet in the master file.

My problem:

Im getting the Run-time error '91': Object variable or With block variable not set on the .Title = "Select A Target Folder" line.

I've tried different solutions to rectify the issue but nothing has yet worked.

My code:

Sub loopAllExcelFilesInFolder()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

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

  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

  myExtension = "*.xls*"

  myFile = Dir(myPath & myExtension)

  Do While myFile <> ""
      Set wb = Workbooks.Open(FileName:=myPath & myFile)
    
      DoEvents
    
      Call cleanDataAndTransfer
    
      wb.Close SaveChanges:=True
      
      DoEvents

      myFile = Dir
  Loop


ResetSettings:
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

I would really appreciate any suggestions on how to solve this bug and any other improvements! Thanks in advance :)

1 Answers1

0

I don't have a Mac to test this but you could try an InputBox.

update - no filter on Dir

Sub loopAllExcelFilesInFolder()

   Sub loopAllExcelFilesInFolder2()

    Const EXT = "csv"

    Dim wb As Workbook, myPath As String, myFile As String
    Dim count As Integer, isWindows As Boolean
    
    myPath = ThisWorkbook.Path & Application.PathSeparator
    myPath = VBA.InputBox("Enter folder", "Folder", myPath)
    If myPath = "" Then Exit Sub

    If Right(myPath, 1) <> Application.PathSeparator Then
        myPath = myPath & Application.PathSeparator
    End If
   
    myFile = Dir(myPath)
    Do While myFile <> ""
        If Right(myFile, Len(EXT)) = EXT Then
 
            Set wb = Workbooks.Open(Filename:=myPath & myFile)
            Call cleanDataAndTransfer
            wb.Close SaveChanges:=True
            count = count + 1

        End If
        myFile = Dir
    Loop
    MsgBox count & " files cleaned", vbInformation
End Sub
CDP1802
  • 13,871
  • 2
  • 7
  • 17