:ような名前のファイルがあるソースフォルダ内エクセルVBAフォルダとサブフォルダ内を検索すると返され、複数のファイルを、私は検索など、Excelのリストから始まるフォルダ内のファイルの数をコピーする必要が
8100 ' cell "A2"
8152 ' cell "A3"
8153 ' cell "A4"
このファイル:
8153.pdf
100_8152.pdf
102_8153.pdf
8153 (2).pdf
これらのファイルを見つけて、別のフォルダにあるすべてのファイルをコピーするにはどうすればよいですか?コードは1つのファイルしか返しませんが、セルの値に一致するすべてのファイルが必要です。私は年単位で整理されたサブフォルダで研究を拡張する必要があります(例: "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はすべてのファイルと一致する必要があります。私はファイルが両方のフォルダに決して置かれていないので、ファイルの名前を変更する必要はありません – ufollettu