Dir()函数不适用于Mac Excel 2011 VBA

嗨,我想列出Excel工作簿所在的子目录中的所有文件。出于某种原因,代码不能超出Dir函数执行。 任何人都可以请指教? 谢谢!

Sub ListFiles() ActiveSheet.Name = "temp" Dim MyDir As String 'Declare the variables Dim strPath As String Dim strFile As String Dim r As Long MyDir = ActiveWorkbook.Path 'current path where workbook is strPath = MyDir & ":Current:" 'files within "Current" folder subdir, I am using Mac Excel 2011 'Insert the headers in Columns A, B, and C Cells(1, "A").Value = "FileName" Cells(1, "B").Value = "Size" Cells(1, "C").Value = "Date/Time" 'Find the next available row r = Cells(Rows.Count, "A").End(xlUp).Row + 1 'Get the first file from the folder 'Note: macro stops working here strFile = Dir(strPath & "*.csv", vbNormal) 'Loop through each file in the folder Do While Len(strFile) > 0 'List the name, size, and date/time of the current file Cells(r, 1).Value = strFile Cells(r, 2).Value = FileLen(strPath & strFile) Cells(r, 3).Value = FileDateTime(strPath & strFile) 'Determine the next row r = r + 1 'Get the next file from the folder strFile = Dir Loop 'Change the width of the columns to achieve the best fit Columns.AutoFit End Sub 

Gianna,你不能在VBA-EXCEL 2011中使用DIR 。我的意思是不支持通配符。 你必须使用MACID来达到这个目的。

看到这个代码示例( TRIED AND TESTED

 Sub Sample() MyDir = ActiveWorkbook.Path strPath = MyDir & ":" 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 

有关MACID的更多详细信息,请参阅此链接

主题:MacIDfunction

链接 : http : //office.microsoft.com/en-us/access-help/macid-function-HA001228879.aspx

编辑:

如果链接永远死亡,我怀疑,这里是一个摘录。

MacIDfunction

用于在Macintosh上将4个字符的常量转换为Dir,Kill,Shell和AppActivate可能使用的值。

句法

MACID(常量)

所需的常量参数由用于指定资源types,文件types,应用程序签名或Apple事件的4个字符组成,例如,用于Excel文件的TEXT,OBIN,“XLS5”(用于Excel 97的“XLS8”),用于Microsoft Word的“W6BN”(Word 97的“W8BN”)等等。

备注

与Dir和Kill一起使用MacID来指定Macintosh文件types。 由于Macintosh不支持*和? 作为通配符,您可以使用四个字符的常量来标识文件组。 例如,以下语句从当前文件夹返回TEXTtypes文件:

Dir(“SomePath”,MacID(“TEXT”))

MacID与Shell和AppActivate一起使用来指定使用应用程序的唯一签名的应用程序。

HTH

 If Dir(outputFileName) <> "" Then Dim ans ans = MsgBox("File already exists.Do you wish to continue(the previous file will be deleted)?", vbYesNo) If ans = vbNo Then Exit Sub Else Kill outputFileName End If End If For listitem = 0 To List6.ListCount() - 1 

对于上面的答案,当我在MacID中拿出“TEXT”时,它对我有用:

 Sub LoopThruFiles() Dim mydir As String Dim foldercount As Integer Dim Subjectnum As String Dim strpath As String Dim strfile As String ChDir "HD:Main Folder:" mydir = "HD:Main Folder:" SecondaryFolder = "Folder 01:" strpath = mydir & SecondaryFolder strfile = Dir(strpath) 'Loop through each file in the folder Do While Len(strfile) > 0 If Right(strfile, 3) = "cef" Then MsgBox (strfile) End If strfile = Dir Loop End Sub