excel - VBA - 将多个选定的文件从一个文件夹复制到另一个
问题描述
我正在寻找一种方法来选择一个文件夹中的多个 .jpg 文件并将其复制到另一个文件夹。这是我正在使用的代码,但它似乎无法将其移动到目标文件。
我还使用了一个 excel 工作表,我在其中粘贴了我想在 A 行中复制的那些文件名。
Sub CopyFiles()
Dim xDir As String
Dim xFile As String
Dim xRow As Long
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim FileExt As String
Dim FNames As String
FromPath = "Directory" 'Folder From
ToPath = "Directory" 'Folder To
Worksheets("Files to Copy").Activate
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then
xDir = .SelectedItems(1)
xFile = Dir(xDir & Application.PathSeparator & "*")
Do Until xFile = ""
xRow = 0
On Error Resume Next
xRow = Application.Match(xFile, Range("A:A"), 0)
If xRow > 0 Then
Name xDir & Application.PathSeparator & xFile As _
ToPath & Cells(xRow, "B").Value
End If
xFile = Dir
Loop
End If
End With
End Sub
解决方案
Sub CopyFiles()
'// Tools -> References -> Microsoft Scripting Runtime
Dim xRow As Long
Dim FSO As FileSystemObject
Dim FromPath$, ToPath$
Dim xFile As File
Dim xFolder As Folder
FromPath = "Directory" 'Folder From
ToPath = "Directory" 'Folder To
Worksheets("Files to Copy").Activate
Set fso = New FileSystemObject
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If Not .Show Then Exit Sub
Set xFolder = FSO.GetFolder(.SelectedItems(1))
For Each xFile In xFolder.Files
On Error Resume Next
xRow = Application.Match(xFile.Name, Range("A:A"), 0)
If Err = 0 Then
xFile.Copy ToPath & Cells(xRow, "B").Value
End If
On Error GoTo 0
Next
End With
End Sub
推荐阅读
- c# - Azure Cosmos DB (EF/Core) - ID 列包含类名
- firebase - Flutter 中的自定义通知声音
- mysql - 如何在 MySQL 查询中使用 count 和 CASE 条件?
- android - 我可以在 Playstore 中更改我的应用的 Playstore URL 吗?
- sql - 通过检查 SQL 中的多列来删除重复行
- python - 仅访问数据框的前 80% 列
- python - 无法在多台机器上运行 mpi4py 程序
- facebook - 您可以在没有页面的情况下使用 Messenger API 吗?
- python - 如何创建红色调试记录器错误消息?
- c - 有人可以解释一下为什么当“字符串”与“%d” fromat 说明符一起使用时,它会给出奇怪的输出