gpt4 book ai didi

excel - VBA - 列出给定文件夹及其所有子文件夹中的给定扩展名的文件名,直到最后一级

转载 作者:行者123 更新时间:2023-12-04 07:15:08 29 4
gpt4 key购买 nike

您好,我正在尝试从多个文件夹及其子文件夹中通过扩展名获取特定文件,但我在执行此任务时遇到了问题。到目前为止我所拥有的是:

Sub ListFiles()

'Declare variables
Dim i As Long

Dim fileName As Variant
fileName = Dir("J:\BREAKDOWNS\*.PDF")

i = 2
While fileName <> ""
Cells(i, 1).Value = Left(fileName, Len(fileName) - 4)
i = i + 1
fileName = Dir
Wend

End Sub
有人可以帮忙吗?
附言
我需要什么,到目前为止我得到了什么
folder = "J:\BREAKDOWNS\*.PDF"

sn = Split(CreateObject("wscript.shell").exec("cmd /c Dir """ & folder & ibox & """ /s /a /b").StdOut.ReadAll, vbCrLf)

Sheets(1).Cells(2, 1).Resize(UBound(sn) + 1) = Application.Transpose(sn)
但它返回完整的地址,在那里我只需要不带扩展名的文件名。

最佳答案

尝试下面的代码,它列出给定文件夹中给定扩展名的文件名及其所有子文件夹,直到新添加的工作表上的最后一级
积分:https://www.youtube.com/watch?v=ddA2_SOaq14

Option Explicit

Sub List_File_Names()
'This macro lists file names of the given extensions in the given folder and _
its all subfolders down to last level on a newly added sheet
'https://stackoverflow.com/questions/68812888/ _
vba-list-file-names-of-the-given-extensions-in-the-given-folder-and-its-all-su

'reference - https://www.youtube.com/watch?v=ddA2_SOaq14
Dim FNameStr As String, ExtStr As String, ExrArr, sn, nWs As Worksheet
Dim regex As Object, mc As Object, f As String, i As Long
Dim fldr As FileDialog

Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
fldr.Show
f = fldr.SelectedItems(1)
f = f & "\"

Set regex = CreateObject("VBScript.regexp")
regex.ignorecase = False
regex.Global = True

ExtStr = InputBox("Enter extensions of filesnames to be listed delimited by comma", _
Default:=".xlsx,.pdf")
ExrArr = Split(ExtStr, ",")

FNameStr = ""

If ExtStr <> "" Then
For i = LBound(ExrArr) To UBound(ExrArr)
FNameStr = FNameStr & (CreateObject("wscript.shell").exec("cmd /c Dir /s /b """ & _
f & """ | findstr """ & ExrArr(i) & """ ").stdout.readall)
Next i
Else
FNameStr = FNameStr & (CreateObject("wscript.shell").exec("cmd /c Dir /s /b """ & _
f & """").stdout.readall)
End If

regex.Pattern = "\S[^\n]+\\" 'to remove folder names from full file name
sn = Split(Replace(regex.Replace(FNameStr, ""), vbCrLf, "|"), "|")
Set nWs = Worksheets.Add(Before:=Sheets(1))
nWs.Cells(1).Resize(UBound(sn) + 1) = Application.Transpose(sn)

End Sub

关于excel - VBA - 列出给定文件夹及其所有子文件夹中的给定扩展名的文件名,直到最后一级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68812888/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com