使用Excel VBA获取文件夹/目录中的文件名列表
问题描述:
我有以下代码,它从我指定的目录中提取文件名。我在互联网上找到它,并将其修改为适合我需要的内容。使用Excel VBA获取文件夹/目录中的文件名列表
问题是我不希望它弹出窗口要求我选择一个文件夹 - 我想使用指定的文件夹。如何更改此代码,以便我不必使用该窗口,或者如果我无法更改该窗口,可以对我的情况做些什么?
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
答
我最终完全改变了我的代码,并没有使用旧的代码。再次,我在互联网上发现了一些代码,并将其修改为适合我需要的内容。
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
答
这是代码的关键部分:
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
您可以指定任何路径你想
答
在我的Excel-2010上,Kelsius的示例仅适用于目录名称中的尾部(右侧)反斜杠:
的FileName = DIR( “C:\桌面\”)
这是我的完整的例子:
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
下一步:了解你发现代码在互联网上...... – 2015-04-02 19:54:48
我意识到我第一次找到的东西,但发现我需要改变它以适应我现在需要的东西。 – Kelsius 2015-04-02 19:56:14