Excel VBA user defined function to find images in

2019-09-07 07:09发布

Currently i am using a function to match image names from excel sheet to image folder, but i want one more thing... that if i save image and forget to add its name in excel then it should show me that i forget to add name. for example if i save 3 images in image folder

16095_1.jpg,16095_2.jpg,16095_3.jpg

and i add image names in excel sheet as

16095_1.jpg,16095_2.jpg

then it should warn me that i forget one image name in excel cell.

my image name format is - 16095_1.jpg,16095_2.jpg

function i am using is...

Function findimage(Path As String, ImageList As String)
Dim results
Dim x As Long
Dim dc 'double comma
results = Split(ImageList, ",")
If Not Right(Path, 1) = "\" Then Path = Path & "\"
For x = 0 To UBound(results)
results(x) = Len(Dir(Path & results(x))) > 0
Next
dc = InStr(ImageList, ",,")
If dc = 0 Then
findimage = Join(results, ",")
Else
findimage = ("Double_comma")
End If
End Function

1条回答
女痞
2楼-- · 2019-09-07 07:51

This function takes a folder path and a variable number of patterns (See MSDN - Parameter Arrays (Visual Basic)). Using the MSDN - Dir Function to iterates over the file names in the folder path and compares them against the patterns with the MSDN - Like Operator (Visual Basic) to count the number of files that match the patterns.

Usage:

  • getFileCount("C:\Users\Owner\Pictures",".gif",".png")
  • getFileCount("C:\Users\Owner\Pictures","*.gif"
  • getFileCount("C:\Users\Owner\Pictures","apple_.gif","banana_.gif", "orange_##.*")
  • getFileCount("C:\Users\Owner\Pictures","#####_#.gif")

Function getFileCount(DirPath As String, ParamArray Patterns() As Variant) As Integer
    Dim MyFile As String
    Dim count As Integer, x As Long
    If Not Right(DirPath, 1) = "\" Then DirPath = DirPath & "\"

    MyFile = Dir(DirPath, vbDirectory)

    Do While MyFile <> ""
        For x = 0 To UBound(Patterns)
            If MyFile Like Patterns(x) Then
                count = count + 1
                Exit For
            End If
        Next

        MyFile = Dir()
    Loop
    getFileCount = count
End Function
查看更多
登录 后发表回答