【问题标题】:Looping through excel files in a folder and performing a procedure on each of them VBA遍历文件夹中的 excel 文件并对每个文件执行一个过程 VBA
【发布时间】:2021-09-23 10:24:35
【问题描述】:

我的目标:

此过程旨在循环遍历指定文件夹中的excel文件并执行子(cleanDataAndTransfer),该子程序旨在清理循环通过的文件中的数据,然后将其粘贴到主文件中的新工作表中.

我的问题:

我收到运行时错误“91”:.Title = "Select A Target Folder" 行上未设置对象变量或块变量。

我尝试了不同的解决方案来纠正这个问题,但没有任何效果。

我的代码:

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

非常感谢有关如何解决此错误和任何其他改进的任何建议!在此先感谢:)

【问题讨论】:

  • 您发布的代码中没有.Title = "Select A Target Folder" 的行。
  • @Storax 这是一个错字,我现在已经更正了 - 谢谢!
  • 用更正的行我没有得到你的 RTE。
  • @Storax 什么是 RTE?
  • RTE=运行时错误。所以,我要说的是代码一直运行到调用.Show 的那一行。

标签: excel vba loops


【解决方案1】:

我没有 Mac 来测试这个,但你可以试试 InputBox。

更新 - 目录上没有过滤器

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

【讨论】:

  • 我试过了,但是出现了这个错误,运行时错误'5':无效的过程调用或参数
  • @Esrom 如果在行myPath = VBA.InputBox("Enter folder", "Folder", myPath) 则将行替换为myPath = "/whatever/your/path/to/files/is/"
  • 抱歉,在这个 myFile = Dir(myPath, MacID("TEXT")) ' mac
  • @Esrom - 查看没有 MacID() 函数的更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 2014-05-11
相关资源
最近更新 更多