MS Access从表中查找VBA查找映像文件名,搜索它们并复制它们

时间:2016-12-23 11:29:03

标签: vba ms-access access-vba

我正在使用Access 2013.我在表格中有一个图像列表。然后我需要搜索一组文件夹(包括子文件夹),找到图像并将它们复制到一个新目录。包含图像名称的表不引用文件路径。

实现这一目标的最佳方法是什么?是否可以遍历表并执行搜索,或者我是否可以将其分解并手动定位每个文件并更新标志以表明它存在,然后返回并复制它们?

不知道如何做到这一点,但不胜感激。

感谢。

1 个答案:

答案 0 :(得分:1)

对于某些导入程序,我不得不操作文件,创建副本等,我创建了一些帮助处理的函数,你可能会发现它们有用:

从VBA创建文件夹:

Public Function folderCreate(filePath As String) As Boolean
    'define variables
    Dim fsoFold As Object

    'set file system object
    Set fsoFold = CreateObject("Scripting.FileSystemObject")

    If Not fsoFold.folderExists(filePath) Then
        'check if folder exists
        fsoFold.CreateFolder (filePath)
    End If

    folderCreate = True

    Set fsoFold = Nothing

End Function

检查文件夹是否存在:

Public Function folderExists(folderPath As String) As Boolean
    'define variables
    Dim fso As Object

    'set file system object
    Set fso = CreateObject("Scripting.FileSystemObject")

    'check if file exists
    If fso.folderExists(folderPath) Then
        folderExists = True
    Else
        folderExists = False
    End If

    Set fso = Nothing

End Function

检查文件是否存在:

Public Function fileExists(filePath As String) As Boolean
     'define variables
     Dim fso As Object

    'set file system object
    Set fso = CreateObject("Scripting.FileSystemObject")

    'check if file exists
    If fso.fileExists(filePath) Then
        fileExists = True
    Else
        fileExists = False
    End If

    Set fso = Nothing

End Function

与此类似,使用movefile将其移动到新位置。

fso.movefile strFullPath, strFullBackUp

编辑:以下子将通过给定文件夹并列出所有JPG图像 - 此代码只是如何查找文件,文件夹以及如何递归遍历它们的示例。

Public Sub listImages(folderPath As String)

    'define variables
    Dim fso As Object
    Dim objFolder As Object
    Dim objFolders As Object
    Dim objF As Object
    Dim objFile As Object
    Dim objFiles As Object
    Dim strFileName As String
    Dim strFilePath As String
    Dim myList As String

    'set file system object
    Set fso = CreateObject("Scripting.FileSystemObject")

    'set folder object
    Set objFolder = fso.GetFolder(folderPath)

    'set files
    Set objFiles = objFolder.files
    Set objFolders = objFolder.subfolders

    'list all images in folder
    For Each objFile In objFiles

        If Right(objFile.Name, 4) = ".jpg" Then
            strFileName = objFile.Name
            strFilePath = objFile.Path
            myList = myList & strFileName & " - " & strFilePath & vbNewLine
        End If

    Next

    'go through all subflders
    For Each objF In objFolders

        'call same procedure for each subfolder
        Call listImages(objF.Path)

     Next

     Debug.Print myList

     Set objFolder = Nothing
     set objFolders = Nothing
     Set objFile = Nothing
     set objF = Nothing
     Set fso = Nothing


End Sub