根据用户输入在文件夹中搜索文件,将该文件复制到新文件夹中

时间:2011-04-28 01:28:56

标签: vba excel-vba excel

我有一个包含很多图片的文件夹。我需要根据用户的输入复制该文件夹中的图片并将其复制到一个新文件夹中:

  1. 用户输入输入。
  2. 代码需要根据输入搜索文件夹中的图片。
  3. 如果找到,则将图片移至新文件夹/其他文件夹。
  4. 我该怎么做?

1 个答案:

答案 0 :(得分:4)

这是如何做到这一点的一个例子。我不知道你的“用户输入”是什么,所以我只是做了一个假设。适当纠正。

Sub CopySomeFiles()
    Dim FSO, sourceFolder, currentFile, filesInSourceFolder
    Dim strSourceFolderPath As String
    Dim strDestinationFolderPath As String
    Dim strUserInput As String
    Set FSO = CreateObject("Scripting.FileSystemObject")

    ' Figure out which file to copy from where to where
    strUserInput = InputBox("Please enter name of file to copy.")
    strSourceFolderPath = "C:\MySourceFolder"
    strDestinationFolderPath = "C:\MyDestinationFolder"

    Set sourceFolder = FSO.GetFolder(strSourceFolderPath)
    Set filesInSourceFolder = sourceFolder.Files

    ' Look at all files in source folder. If name matches,
    ' copy to destination folder.
    For Each currentFile In filesInSourceFolder
        If currentFile.Name = strUserInput Then
            currentFile.Copy (FSO.BuildPath(strDestinationFolderPath, _
                currentFile.Name))
        End If
    Next

End Sub
相关问题