Excel VBA用户定义函数,用于查找文件夹中的图像(将excel名称与图像的文件夹名称相匹配)

时间:2016-11-29 05:06:41

标签: excel vba excel-vba

目前我正在使用一个功能来匹配excel表格到图像文件夹中的图像名称,但我还想要一件事...如果我保存图像并忘记在excel中添加其名称那么它应该告诉我忘记了添加名称。 例如,如果我在图像文件夹中保存3个图像

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

我在excel表中添加图像名称为

16095_1.jpg,16095_2.jpg

那么它应该警告我忘记了excel单元格中的一个图像名称。

我的图片名称格式为 - 16095_1.jpg,16095_2.jpg

我正在使用的功能是......

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 个答案:

答案 0 :(得分:1)

此函数采用文件夹路径和可变数量的模式(请参阅MSDN - Parameter Arrays (Visual Basic))。使用MSDN - Dir Function迭代文件夹路径中的文件名,并将它们与MSDN - Like Operator (Visual Basic)的模式进行比较,以计算与模式匹配的文件数。

<强>用法:

  • getFileCount( “C:\用户\所有者\图片”, “ .gif注意”, “ .PNG”)
  • getFileCount( “C:\用户\所有者\图片”, “* GIF。”
  • getFileCount(“C:\ Users \ Owner \ Pictures”,“apple_ .gif”,“banana _ .gif”,“orange _ ##。*”)
  • getFileCount( “C:\用户\所有者\图片”, “##### _#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