VBA how to find a folder name which is include Today's date

Viewed 48

I need to check if there is a folder which name is include Today's date.

This is the path looks like;

B:\NOS\EIhracat\Credit\2022\34- 17.09.2022\Nakit List.xlsx

But I have a problem about folder names. There are a lot of subfolder looks like "34- 17.09.2022" or "15- 16.09.2022" etc. under Years. The numbers before the date are changing randomly, I don't need them.

How can I find the folder name which is ends with Today's Date (or starts with Today's date. I can move the numbers after date)

I tried this one.

dtToday = Format(Date, "dd.mm.yyyy")
dtYear = Format(Date, "yyyy")
Ihracat = "B:\NOS\EIhracat\Credit\" & dtYear & "\"


strFileName = Ihracat & "*dtToday & "\" & "Nakit List.xlsx"
strFileExists = Dir(strFileName)


If strFileExists = "" Then
    MsgBox "Can't find!"
Else
1 Answers

Please, use the next function. If works if you know the folder where the searched one containing Date in its name exists:

Function getFoldPath(dirFolder As String, strToFind As String) As String
    Dim fldName As String
    If Right(dirFolder, 1) <> "\" Then dirFolder = dirFolder & "\"
    fldName = Dir(dirFolder & "*" & strToFind & "*", vbDirectory)

    Do While fldName <> ""
        If fldName <> "." And fldName <> ".." Then
            ' Use bitwise comparison to make sure dirFolder is a directory.
            If (GetAttr(dirFolder & fldName) And vbDirectory) = vbDirectory Then
                getFoldPath = dirFolder & fldName: Exit Function
            End If
        End If
        fldName = Dir
    Loop
End Function

You can call the function in the next way:

Sub testGetFoldPath_()
    Const parentFolder As String = "B:\NOS\EIhracat\Credit\2022\" 'take care of the ending backslash ("\")
    Debug.Print getFoldPath(parentFolder, CStr(Format(Date, "dd.mm.yyyy")))
End Sub
Related