查看: 23  |  回复: 0
  VBA代码 遍历图片文件
楼主
发表于 2025年3月18日 14:30
Private PicName() As String    '定义一个数组装入图片名称

Sub GetPicName(ByVal sPath As String, ByVal Filter As String)    '这是获取指定文件夹下指定后缀名的文件名称的过程,装入数组picname()中
    Dim sDir As String, sFilter() As String
    Dim lngFilterIndex As Long, lngIndex As Long, lngfiles As Long
    sFilter = Split(Filter, ",")
    If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
    
    For lngFilterIndex = LBound(sFilter) To UBound(sFilter)
        sDir = Dir(sPath & sFilter(lngFilterIndex))
        Do While Len(sDir) > 0
            lngfiles = lngfiles + 1
            ReDim Preserve PicName(1 To lngfiles)
            PicName(lngfiles) = sPath & sDir    '全路径
            sDir = Dir
        Loop
    Next
End Sub

Sub Sample1()    '这是调用,举例,获取用户选择文件夹下后缀名为jpg,gif,png,wmf的文件名称
    Dim i%
    On Error Resume Next
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = True Then
            Call GetPicName(.SelectedItems(1), "*.jpg,*.gif,*.png,*.wmf")    '获得图片文件,后缀可自己制定
        End If
        
        If IsEmpty(PicName) Then MsgBox "没有找到图片文件": Exit Sub
        For i = 1 To UBound(PicName)
            Debug.Print PicName(i)    '处理文件列表
            '自己添加对应处理代码,文件名为PicName(i)
        Next
    End With
End Sub


您需要登录后才可以回帖 登录 | 立即注册
【本版规则】请勿发表违反国家法律的内容,否则会被冻结账号和删贴。
用户名: 立即注册
密码:
2020-2025 MaNongKu.com