检查文件名是否包含字符串

时间:2018-01-30 11:02:16

标签: excel vba excel-vba excel-2010

在我的项目中,我在Excel工作表的第一列中有一个产品列表,我定期从网站下载产品图像,而不是将它们存储在每个项目的名称不同的文件夹中。下载过程结束后,我删除了不必要的图像文件。

删除过程后,我想知道文件夹中每个产品剩下多少张图片。

示例:

我在第一列中的产品名称列表>>> click for image

我的图片文件夹>>> click for image

我想要的是每个产品的文件夹上的图像数量>>> click for image

如果我制作excel公式来为第二列上的每个产品写入图像数量,在相应的产品名称单元格旁边,我将能够轻松地看到任何产品缺少图像。之后,我将报告没有图像的产品列表。

图像的所有名称由“productname”和“_ *”两部分组成,*是数字。由于产品名称与图像文件名称不同,因此图像列数量中的值必须是名称中包含产品名称的图像编号。

是否可行?我对VBA有非常基本的了解。

这是我尝试使用 @Miguel_Ryu

的方法时得到的结果

我编写的函数>>> click here

我的文件夹>>> click here

我得到错误>>> click here

模块>>> click here

1 个答案:

答案 0 :(得分:1)

尝试此功能,它会返回包含strToFind的文件数。

您可以这样称呼它:
fileCount = loopThroughFilesCount("C:\yourPath\yourFiles\", "yourString")

Function loopThroughFilesCount(dirFolder As String, strToFind As String) As Double

    Dim filePath As Variant
    filePath = Dir(dirFolder)
    While (filePath <> "")
        If InStr(filePath, strToFind) > 0 Then
            filesCount = filesCount + 1
        End If
        filePath = Dir
    Wend

    loopThroughFilesCount = filesCount

End Function

编辑: 将上述内容作为宏运行。

Sub countFiles()

    Set last = Range("A:A").Find("*", Cells(1, 1), searchdirection:=xlPrevious)

    For n = 2 To last.Row
        Cells(n, 2).Value = loopThroughFilesCount("C:\Users\yalinbah\Desktop\boyner\gör‌​‌​seller2\Tekstil\", Cells(n, 1).Value)
    Next

End Sub

Function loopThroughFilesCount(dirFolder As String, strToFind As String) As Double

    Dim filePath As Variant
    filePath = Dir(dirFolder)
    While (filePath <> "")
        If InStr(filePath, strToFind) > 0 Then
            filesCount = filesCount + 1
        End If
        filePath = Dir
    Wend

    loopThroughFilesCount = filesCount

End Function
相关问题