Функция 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
Ответы
Ответ 1
Gianna, вы не можете использовать DIR
как в VBA-EXCEL 2011. Я имею в виду, что подстановочные знаки не поддерживаются. Вы должны использовать 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
Тема: Функция MACID
Ссылка: http://office.microsoft.com/en-us/access-help/macid-function-HA001228879.aspx
EDIT:
Если эта связь когда-либо умирает, я сомневаюсь, вот выдержка.
Функция MACID
Используется на Macintosh для преобразования 4-значной константы в значение, которое может использоваться Dir, Kill, Shell и AppActivate.
Синтаксис
MACID (константа)
Требуемый константный аргумент состоит из 4-х символов, используемых для указания типа ресурса, типа файла, подписи приложения или события Apple, например, TEXT, OBIN, "XLS5" для файлов Excel ( "XLS8" для Excel 97) Microsoft Word использует "W6BN" ( "W8BN" для Word 97) и т.д.
Примечания
MacID используется с Dir и Kill для указания типа файла Macintosh. Поскольку Macintosh не поддерживает * и? в качестве подстановочных знаков вы можете использовать четырехсимвольную константу, чтобы идентифицировать группы файлов. Например, следующий оператор возвращает файлы типа TEXT из текущей папки:
Dir ( "SomePath", MacID ( "ТЕКСТ" ))
MacID используется с Shell и AppActivate для указания приложения с использованием уникальной подписи приложения.
НТН
Ответ 2
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
Ответ 3
Для ответа выше, это сработало для меня, когда я вынул "ТЕКСТ" в MacID:
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