Dir() in Excel for Mac 2016 causes crash - excel

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:
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

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)

Related

Excel VBA Dir() Error when file type changes

I'm trying to better understand the Dir function. I have a Dir loop to take action on all .csv files in the directory, but when the loop comes across another file type, like .txt, it will error instead of moving on to the next .csv. item.
This is the relevant portion of my code.
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
strWorkbook = Dir(strSourceExcelLocation & "*.csv*")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport)
'Get next workbook
strWorkbook = Dir
'Close Excel workbook without making changes
wbktoExport.Close False
Loop
So if there are only .csv files in the directory, then this works fine. When it comes across another file type, an error occurs.
The error is on line
strWorkbook = Dir
Run-time error 5: Invalid procedure call or argument
Am I missing something with the way I use the wildcards in the .csv at the beginning?
Thank you
Solved my issue.
The problem seems to have been because when I called another procedure, I had another Dir in that sub to create a new folder if one didn't already exist. So basically I had a Dir in a Dir, which apparently is bad.
I moved the folder creation part to the very beginning of my procedure, so it is executed before I begin the Dir for looping through all the CSV files.
Option Explicit
Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String, wbktoExport As Workbook, strSourceExcelLocation As String, fldr As String, strTargetPDFLocation As String, d As String
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\"
'***** Creating a folder to save the PDFs in. Naming the folder with today's date *****
d = Format(Date, "mm-dd-yyyy")
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\" & d & "\"
If Len(Dir(strTargetPDFLocation, vbDirectory)) = 0 Then MkDir strTargetPDFLocation
fldr = InputBox("Input the EXACT Folder Name that you want to create PDFs for")
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.csv")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport, strTargetPDFLocation)
'Close Excel workbook without making changes
wbktoExport.Close False
'Get next workbook
strWorkbook = Dir
Loop
End Sub
Try to hardcode the path and give it a try again. Probably the error is something really small in the hardcoding. E.g., in the code below, replace C:\Users\username\Desktop\AAA\ with the path of the file. Then run it. Do not forget the last \. It should work:
Sub TestMe()
Dim workbookPath As String
workbookPath = Dir("C:\Users\username\Desktop\AAA\" & "*.csv")
Do While Len(workbookPath) > 0
Debug.Print workbookPath
workbookPath = Dir
Loop
End Sub

How to loop and open all csv files in my current folder in VBA

I randomly create a new folder on my desktop, in this folder I have one template file with .xlsm extension, which contains my VBA code. Meanwhile I have several csv files saved in the same folder with my raw data.
The purpose is looping through all those csv files one by one, open it, and copy some data and paste to my template file(I know how to do this part) from it and close it after all operations are done.
Currently I meet a problem about how to loop through my folder and open those csv one by one. I didn't set a specific folder name, since I want to share it with other people to use,therefore I use Application.ActiveWorkbook.Path to get the path for my current folder.
Here is my code:
Option Explicit
Sub Range_End_Method()
Dim Dir As String
Dim i As String
Application.ScreenUpdating = False
Dir = Application.ActiveWorkbook.Path & "\"
For Each i In Dir.Files
Debug.Print i.Name
If (i.Name Like "*.csv") Then
Workbooks.Open (i.Path)
End If
Next
End Sub
I'm guessing you want to use the Dir function. To use that, make a call to it, specifying folder and file type in the first call, then call it empty until it returns an empty string. Like this:
Folder = Dir(Application.ActiveWorkbook.Path & "\*.csv")
Do While Folder <> ""
Debug.Print Folder
Workbooks.Open Folder
Folder = Dir()
Loop
You can use this function and macro.
Juste replace MsgBox (myFile + "OK") by the action you want to execute.
FUNCTION
Function ClasseurOuvert(NomFich)
On Error Resume Next
Workbooks(NomFich).Activate
If Err <> 0 Then Workbooks.Open FileName:=NomFich
On Error GoTo 0
End Function
MACRO
Sub LoopFiles()
Dim myPath As String, myFile As String
myPath = Application.ActiveWorkbook.Path & "\"
myFile = Dir(myPath & "\*.*")
Do While myFile <> "" And myFile Like "*.csv"
Call ClasseurOuvert(myPath & "\" & myFile)
With Workbooks(myFile)
MsgBox (myFile + "OK")
End With
Workbooks(myFile).Save
Workbooks(myFile).Close
myFile = Dir()
Loop
End Sub

Excel VBA - Check if file exists using Wildcard and open the file

I wish to check whether a file exist in a folder on my computer. I have below, which can see if a specific file exists:
Function FileExists(sFile As String)
sPath = "M:\User\" & sFile & ".xlsm"
FileExists = Dir(sPath) <> ""
End Function
However, my files are named like: Filename - Version xx.xlsm and is updated regularly. Please note that there will only be one file in the folder, but the filename can vary.
How can I search in the folder using wildcard:
Filename - Version % % and then, if it find any file, open the file afterwards?
One option would be to Open the file inside of the FileExists function. However, I would not recommend doing this. The function should do exactly what the name implies and nothing more.
Another option is restructure your code a little bit:
Private Sub OpenFile()
Dim FileName As String
FileName = GetFile("Filename - Version*")
If FileName <> "" Then
'open FileName as needed
End If
End Sub
Private Function GetFile(sFile As String) As String
sPath = "M:\User\" & sFile & ".xlsm"
GetFile = Dir(sPath)
End Function

How do you open a pdf file with VBA code for a relative file path?

I am trying to find the command and correct coding to open a PDF file with a relative file path to the active excel file. The code below works fine as a link directly to the file. However, I just need this code snippet to find the PDF file that is sitting in the same file as the opened excel file and open accordingly.
Sub OpeningPDF()
'ThisWorkbook.FollowHyperlink "C:\Users\Michael\My Documents\totals\copy.pdf"
End Sub
I tried working with ThisWorkbook.path but nothing I tried with that worked or seemed to be outdate. Any help in this matter would be much appreciated.
I have found two solutions to this:
The first one is using the built-in Shell() function. This should automatically resolve the relative path (relative to the applications current working directory):
Public Sub StartExeWithArgument()
Dim strFilename As String
strFilename = "../folder/file.pdf"
Call Shell(strFilename, vbNormalFocus)
End Sub
The second one uses the Shell.Application COM Object and will basically do the same as the first one.
Sub runit()
Dim Shex As Object
Set Shex = CreateObject("Shell.Application")
tgtfile = "../folder/file.pdf"
Shex.Open (tgtfile)
End Sub
If you start with ThisWorkbook.Path and your relative-reference, then trim a layer off for every "..\" in the relative reference, you'll get the path.
Function RelativeToAbsolutePath(ByVal RelativePath As String) AS String
Dim TempStart AS String, TempEnd AS String
TempStart = ThisWorkbook.Path
TempEnd = RelativePath
If Left(TempEnd,1) = "\" Then TempEnd = Mid(TempEnd,1)
RelativeToAbsolutePath = ""
On Error GoTo FuncErr
While Left(TempEnd,3)="..\" AND InStrRev(TempStart,"\")>0
TempStart = Left(TempStart,InStrRev(TempStart,"\")-1) 'Remove 1 layer from Workbook path
TempEnd = Mid(TempEnd,4) 'Remove 1 instance of "..\"
Wend
RelativeToAbsolutePath = TempStart & "\" & TempEnd 'Stitch it all together
FuncErr: 'You may want a DIR(..) check to see if the file actually exists?
End Function
You can then open it with Shell

Loop though files in a Folder on Mac OS X - VBA Excel 2011

I am trying to loop through files in a folder on Mac OS X using VBA Excel 2011. I tried the following code, but it does not work.
Sub ListAllFilesInDir()
Dim strFile As String
Dim strPath1 As String
strPath1 = ActiveWorkbook.FullName
MsgBox strPath1
strFile = Dir(strPath1)
MsgBox strFile
strFile = Dir()
MsgBox strFile
strFile = Dir()
MsgBox strFile
End Sub
I get the name of the active workbook when the program reaches the first MsgBox strFile. I read somewhere that using Dir without an argument results in the next file in the folder. But that does not work for me. I get an empty message box for the second MsgBox strFile command and an error (Runtime error 5: Invalid Procedure call or argument" for the third MsgBox strFile command. I have 4 files in the folder that I am trying to loop through.
Also, what would I do to list only ".xslx" files
Here's a link to a description of the dir() function. Your issue is that dir(strPath1) will set the dir function to return all instances of that EXACT filename in that path, which is only ever going to be a single file. If you'd like all files ending in ".xlsx" try:
dir(ActiveWorkbook.Path & application.PathSeparator & "*.xlsx")
Also, if you have an arbitrary number of files you want to loop through try the following code. It works becuase dir returns an empty string after it's returned the last file:
Sub WorkWithFiles()
Const PATH = "C:\"
Dim file As String
file = Dir(PATH & Application.PathSeparator & "*.xlsx")
Do Until file = ""
'Run some code on the file in the file variable
Debug.Print file
'Then get the next file
file = Dir("")
Loop
End Sub

Resources