使用Excel VBA获取文件夹/目录中的文件名列表
我有下面的代码,从我指定的目录拉文件名。 我在互联网上find它,并修改它为我所需要的工作。
问题是我不希望它popup窗口要求我select一个文件夹 – 我想使用指定的文件夹。 如何更改此代码,以便我不必使用该窗口,或者如果我无法更改,我该如何处理我的情况?
Dim xRow As Long Dim xDirect$, xFname$, InitialFoldr$ InitialFoldr$ = "C:\Desktop" '<<< Startup folder to begin searching from With Application.FileDialog(msoFileDialogFolderPicker) .InitialFileName = Application.DefaultFilePath & "\" .Title = "Please select a folder to list Files from" .InitialFileName = InitialFoldr$ .Show If .SelectedItems.count <> 0 Then xDirect$ = .SelectedItems(1) & "\" xFname$ = Dir(xDirect$, 7) Do While xFname$ <> "" ActiveCell.Offset(xRow) = Left(xFname$, InStrRev(xFname$, ".") - 1) xRow = xRow + 1 xFname$ = Dir Loop End If End With
这是代码的关键部分:
xDirect$ = .SelectedItems(1) & "\" xFname$ = Dir(xDirect$, 7) Do While xFname$ <> "" ActiveCell.Offset(xRow) = Left(xFname$, InStrRev(xFname$, ".") - 1) xRow = xRow + 1 xFname$ = Dir Loop
如果您将该块的第一行更改为
xDirect$ = My_Path_With_Trailing_Slash
你可以指定你想要的任何path
我最终完全改变了我的代码,而不是使用旧的代码。 再次,我在互联网上发现了一些代码,并修改它为我所需要的工作。
Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim FileArray() As Variant Dim FileCount As Integer Dim FileName As String Dim rng As Range Dim Idx As Integer FileCount = 0 FileName = Dir("C:\Desktop") ' Loop until no more matching files are found Do While FileName <> "" FileCount = FileCount + 1 ReDim Preserve FileArray(1 To FileCount) FileArray(FileCount) = FileName FileName = Dir() Loop GetFileList = FileArray Set rng = ActiveCell For Idx = 0 To FileCount - 1 ActiveCell.Offset(Idx, 0).Value = Left(FileArray(Idx + 1), InStrRev(FileArray(Idx + 1), ".") - 1) Next Idx Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True
在我的Excel-2010上,Kelsius的例子只适用于目录名称中的尾部(右)反斜杠:
FileName = Dir(“C:\ Desktop \ ”)
这是我完整的例子:
Public Sub ReadFileList() Dim bkp As String Dim FileArray() As Variant Dim FileCount As Integer Dim FileName As String Dim Idx As Integer Dim rng As Range bkp = "E:\Flak\TRGRES\1\" If bkp <> "" Then FileCount = 0 FileName = dir(bkp) Do While FileName <> "" Debug.Print FileName FileCount = FileCount + 1 ReDim Preserve FileArray(1 To FileCount) FileArray(FileCount) = FileName FileName = dir() Loop End If End Sub