2015-04-02 107 views
0

我有以下代碼,它從我指定的目錄中提取文件名。我在互聯網上找到它,並將其修改爲適合我需要的內容。使用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 

回答

0

我最終完全改變了我的代碼,並沒有使用舊的代碼。再次,我在互聯網上發現了一些代碼,並將其修改爲適合我需要的內容。

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 
+3

下一步:瞭解你發現代碼在互聯網上...... – 2015-04-02 19:54:48

+0

我意識到我第一次找到的東西,但發現我需要改變它以適應我現在需要的東西。 – Kelsius 2015-04-02 19:56:14

1

這是代碼的關鍵部分:

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 

您可以指定任何路徑你想

0

在我的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 
相關問題