Dir() in Excel for Mac 2016 causes crash

2019-09-16 12:16发布

I am trying to iterate through files using Dir, and I understand that it works differently on Mac than windows. This question has been helpful, but I have been unable to implement the solution suggested. The first call to Dir successfully returns a desired filename, but the second call crashes excel. I would like to implement a pattern like this:

Sub printFileNames()
  Dim path as String
  Dim fileName as String
  path = ThisWorkbook.Path & "/SUBFOLDER/"
  fileName = Dir(path, MacID("XLSX"))
  While fileName <> ""
    MsgBox fileName
    fileName = Dir 'This CRASHES EXCEL
  Wend
End Sub

Here is a screenshot of the error message, upon crash:enter image description here

Is this a known bug? Am I using Dir incorrectly for the Mac version of Excel 2016?

EDIT: I have also tried using this exact solution, posted in the above linked question:

Sub Sample()
MyDir = ActiveWorkbook.Path
strPath = MyDir & ":SUBFOLDER:"

strFile = Dir(strPath, MacID("TEXT"))

'Loop through each file in the folder
Do While Len(strFile) > 0
    If Right(strFile, 3) = "csv" Then
        Debug.Print strFile
    End If

    strFile = Dir    
Loop
End Sub

But this gives a "File Not Found" error, even though there are both .csv, .txt, and .xlsx files in the specified folder. Using:/SUBFOLDER/ instead of :SUBFOLDER: prints the appropriate file name for the first loop, but crashes upon calling strFile = Dir

1条回答
等我变得足够好
2楼-- · 2019-09-16 12:57

Use Ron de Bruin's macscript:

https://www.rondebruin.nl/mac/mac013.htm Loop through Files in Folder on a Mac (Dir for Mac Excel)

查看更多
登录 后发表回答