![](/img/trans.png)
[英]VBA; how to extract all files names from a folder - without using Application.FileDialog object
[英]Excel VBA, import the names of all files in the folder without using Application.FileDialog()
我有一个文件夹(每次都是一个文件夹-因此,我不需要浪费时间通过Application.FileDialog来选择它),并且我需要将所有文件名提取到Excel列C中。
这是我在此处使用Application.FileDialog()在stackoverflow上找到的代码,但是我想对文件夹的路径(C:\\ Users \\ michal \\ SkyDrive \\ csv \\ bossa \\ mstcgl_csv)进行硬编码。
另一个问题(重要)是xDirectory $,xFname $和InitialFoldr $变量末尾的$符号,为什么我不能将它们声明as String
? ? 这些变量不是字符串吗? ?
这是代码:
Sub GetFileNames()
Dim Lista As Worksheet
Dim xRow As Long
Dim xDirectory$
Dim xFname$
Dim InitialFoldr$
Dim start As Double
Dim finish As Double
Dim total_time As Double
start = Timer ' remember time when macro starts.
ThisWorkbook.Sheets("Lista").Range("C1").Select
InitialFoldr$ = "C:\Users\michal\SkyDrive\csv\bossa\"
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr$
.Show ' creates list of files ? ? ?
If .SelectedItems.Count <> 0 Then
xDirectory$ = .SelectedItems(1) & "\"
xFname$ = Dir(xDirectory$, 7)
Do While xFname$ <> ""
ThisWorkbook.Sheets("Lista").ActiveCell.Offset(xRow, 0) = xFname$
ActiveCell.Offset(xRow) = xFname$
xRow = xRow + 1
xFname$ = Dir
Loop
End If
End With
finish = Timer ' Set end time.
total_time = Round(finish - start, 3) ' Calculate total time.
MsgBox "This code ran successfully in " & total_time & " seconds", vbInformation
End Sub
你们可以帮我吗? 我只是学习我的VBA基础知识,但我仍然不了解很多事情。 并请回答$符号问题:-)
此行将Application.FileDialog
的路径写入字符串:
xDirectory$ = .SelectedItems(1) & "\"
现在,您只需要将文件夹硬编码为该字符串:
xDirectory$ = "C:\Users\michal\SkyDrive\csv\bossa\"
并删除所有与FileDialog
部分有关的代码。
至于“ $”部分,请参见上面的@BrakNicku的答案。
报废FileDialog
并直接使用Dir
函数:
Sub GetFileNames()
Const InitialFoler As String = "C:\Users\michal\SkyDrive\csv\bossa\"
Dim Lista As Worksheet
Dim filename As String
Dim xRow As Long
Dim start As Double, finish As Double, total_time As Double
start = Timer ' remember time when macro starts.
xRow = 1
filename = Dir(InitialFoler & "*.*")
With ThisWorkbook.Sheets("Lista")
Do While Len(filename) > 0
.Range("C" & xRow).Value = filename
xRow = xRow + 1
filename = Dir
Loop
End With
finish = Timer ' Set end time.
total_time = Round(finish - start, 3) ' Calculate total time.
MsgBox "This code ran successfully in " & total_time & " seconds", vbInformation
End Sub
您可以在此处阅读有关Dir
函数的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.