vba 在不使用循环的情况下确定文件夹中特定类型的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5548231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:56:56  来源:igfitidea点击:

Determine files of a specific type in a folder without using loop

vbaexcel-vbaexcel

提问by strcompnice

Is there any way to use the FileSystemObject in VBA to determine the number of files of a specific type, such as .PDF, in a folder without using a loop such as

有没有什么方法可以在 VBA 中使用 FileSystemObject 来确定文件夹中特定类型(例如 .PDF)文件的数量,而无需使用循环,例如

For Each file In folder.Files
    'Check file type and count
Next

回答by Alex K.

You can do this without the FSO dependency while also negating the need to examine the file extension manually;

您可以在不依赖 FSO 的情况下执行此操作,同时也无需手动检查文件扩展名;

dim file as String, countOf As Long
file = Dir$("c:\xxxxxx\*.pdf")
Do until file = ""
    countOf = (countOf + 1)
    file = Dir$()
Loop

MsgBox countOf

回答by murali

For Excel, you need to use a loop. The loop really won't take that long, but, if for some reason your detest loops and you must have a one liner, then batch is the way to go.

对于 Excel,您需要使用循环。循环真的不会花那么长时间,但是,如果由于某种原因你讨厌循环并且你必须有一个单衬,那么批处理就是要走的路。

I didn't test it but create a text file in the directory, call it whatever.bat, right click the file and select edit (or edit with notepad++). Then insert the following code:

我没有测试它,而是在目录中创建一个文本文件,调用它whatever.bat,右键单击该文件并选择编辑(或使用记事本++进行编辑)。然后插入以下代码:

set /a counter = 0
for /f %%f in (*.pdf) do set /a count += 1

echo counter: %counter%
pause

Save the file, and then double-click to open and run the program.

保存文件,然后双击打开并运行程序。