搜索带有目录的文件-多次匹配 [英] Searching for files with dir - Multiple hits
问题描述
我有一个遍历文件夹的宏,并使用"dir"功能查找活动文件夹中是否存在文件,并将文件名放在单元格中.
I have a macro that iterate through folders and use the "dir"-function to find out if a file exist in the active folder, and puts the filename in a cell.
问题在于它可能是两个或多个文件满足搜索要求.
The problem is that it might be two or more files satisfies the search.
Dir(subfolder & "\Kommunesvar*")
如果有两个以"Kommunesvar"开头的文件,如何在指定的子文件夹中获得两个结果?Dir返回文件名,但我两个都想要.
How can I get both two results in a specified subfolder if there are two files starting with "Kommunesvar"? Dir returns the filename, but I want both.
推荐答案
您如何使用 DIR
.下面的代码将为您提供所有以 Kommunesvar
开头的文件,它们都是Excel文件.
How are you using DIR
. The below code will give you all the files which start with Kommunesvar
and are Excel Files.
Option Explicit
Sub Sample()
Dim subfolder As String
Dim sDir
subfolder = "C:\Temp"
sDir = Dir$(subfolder & "\Kommunesvar*.xls*", vbNormal)
Do Until LenB(sDir) = 0
Debug.Print subfolder & sDir
sDir = Dir$
Loop
End Sub
如果要将所有文件名存储在一个变量中,那么也可以使用它.
If you want to store all the files names in one variable then you can use this as well.
Sub Sample()
Dim subfolder As String, FileNames As String
Dim sDir
subfolder = "C:\Temp"
sDir = Dir$(subfolder & "\Kommunesvar*.xls*", vbNormal)
Do Until LenB(sDir) = 0
If FileNames <> "" Then
FileNames = FileNames & "; " & subfolder & sDir
Else
FileNames = subfolder & sDir
End If
sDir = Dir$
Loop
Debug.Print FileNames
End Sub
这篇关于搜索带有目录的文件-多次匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!