Searching for files with dir - Multiple hits

空扰寡人 提交于 2019-12-31 04:30:11

问题


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*")

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.


回答1:


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


来源:https://stackoverflow.com/questions/11291573/searching-for-files-with-dir-multiple-hits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!