【发布时间】:2017-02-12 15:55:27
【问题描述】:
我必须从 Excel 列表开始搜索并复制文件夹中的多个文件,例如:
8100 ' cell "A2"
8152 ' cell "A3"
8153 ' cell "A4"
在源文件夹中有这样的文件:
8153.pdf
100_8152.pdf
102_8153.pdf
8153 (2).pdf
如何找到这些文件并将所有匹配的文件复制到单独的文件夹中?该代码仅返回一个文件,但我需要与单元格值匹配的所有文件。我还需要扩展我对按年组织的子文件夹的研究(即:“D:\myfolder\2015”、“D:\myfolder\2016”等)。 感谢 user3598756,我现在正在使用此代码:
Option Explicit
Sub cerca()
Dim T As Variant
Dim D As Variant
T = VBA.Format(VBA.Time, "hh.mm.ss")
D = VBA.Format(VBA.Date, "yyyy.MM.dd")
Dim Source As String
Dim Dest As String
Dim Missed As String
Dim fileFound As String
Dim CodiceCS As Variant
Dim cell As Range
Source = "D:\myfolder\"
Dest = "D:\myfolder\research " & D & " " & T
If Dir(Dest, vbDirectory) = "" Then MkDir Dest '<--| create destination folder if not alerady there
With Worksheets("Cerca") '<-- reference your worksheet with pdf names
For Each cell In .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants) '<-- loop through its column "A" cells with "constant" (i.e. not resulting from formulas) values from row 2 down to last non empty one
CodiceCS = VBA.Left((cell.Value), 4)
fileFound = Dir(Source & "\" & CodiceCS & "\*" & cell.Value & "*.Pdf") '<-- look for a source folder file whose name contains the current cell value
If fileFound <> "" Then '<-- if found...
FileCopy Source & "\" & CodiceCS & "\" & fileFound, Dest & "\" & fileFound '<-- ...copy to destination folder
Else '<--otherwise...
Missed = Missed & cell.Value & vbCrLf '<--... update missing files list
End If
Next cell
End With
If Missed <> "" Then '<-- if there's any missing file
Dim FF As Long
FF = FreeFile
Open (Dest & "\" & "MissingFiles.txt") For Output As #FF
Write #FF, VBA.Left(Missed, Len(Missed) - 2)
Close #FF
End If
MsgBox "OK"
Shell "explorer.exe " + Dest, vbNormalFocus
End Sub
【问题讨论】:
-
8153 是否应该与包含值 8153 的所有文件匹配?即 8153.pdf、102_8153.pdf 和 8153 (2).pdf。
-
如果
filefound位于 2015 和 2016 文件夹中,您是否在移动到目标文件夹时重命名文件? -
是的,8153 应该与您所说的所有文件匹配;我不需要重命名文件,因为文件永远不会位于两个文件夹中
-
我的答案中的代码应该可以工作 - 您可以通过在
FileFound = TRUE之后放置一个Exit For来加速它。如果该文件从未位于这两个文件夹中,您最好停止查找它。
标签: excel string vba search directory