vba 根据用户输入在文件夹中搜索文件,将该文件复制到新文件夹中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5812606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search file in folder based on input from user, copy that file into a new folder
提问by ril
I have a folder that contains a lot of pictures. I need to copy the pictures in that folder based on the input by the user and copy it into a new folder:
我有一个文件夹,里面有很多图片。我需要根据用户的输入复制该文件夹中的图片并将其复制到一个新文件夹中:
- User enters input.
- The code needs to search for the pictures in the folder based on the input.
- If found, the pictures is than move to a new folder/another folder.
- 用户输入。
- 代码需要根据输入搜索文件夹中的图片。
- 如果找到,图片将移动到新文件夹/另一个文件夹。
How do I do this?
我该怎么做呢?
回答by Jean-Fran?ois Corbett
This is an example of how to do it. I don't know what your "user input" is, so I just made an assumption. Rectify as appropriate.
这是如何执行此操作的示例。我不知道你的“用户输入”是什么,所以我只是做了一个假设。酌情纠正。
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