I'd like to copy all files with pdf as extension to a new folder (with name from a cell)
I've created below code:
Public Sub MyFileprojectTF()
Dim startPath As String
Dim myName As String
Dim SourceFileName As String, DestinFileName As String
Dim FSOFile As Object
Dim FSOFolder As Object
FolderName = "C:\Users\320105013\Desktop\DXR\"
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.getfolder(FolderName)
Set FSOFile = FSOFolder.Files
Set fso = CreateObject("Scripting.Filesystemobject")
startPath = "C:\Users\320105013\Desktop\DXR Test files\"
myName = ActiveSheet.Range("B3").Text ' Change as required to cell holding the folder title
If myName = vbNullString Then myName = "Testing"
Dim folderPathWithName As String
folderPathWithName = startPath & Application.PathSeparator & myName
If Dir(folderPathWithName, vbDirectory) = vbNullString Then
MkDir folderPathWithName
Else
MsgBox "Folder already exists"
Exit Sub
End If
ActiveWorkbook.FollowHyperlink startPath & myName
SourceFileName = "C:\Users\320105013\Desktop\DXR\" & (FSOFile)
DestinFileName = startPath & myName & "\"
For Each FSOFile In FSOFile
If FSOFile Like "*.pdf" Then
FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
Next
End Sub
I get the following error:
"Wrong number of arguments"
on FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName.
You are using FSOFile twice as 2 different variables... see the 3 comments I added.
Public Sub MyFileprojectTF()
Dim startPath As String
Dim myName As String
Dim SourceFileName As String, DestinFileName As String
Dim FSOFile As Object
Dim FSOFiles As Object ' ADD THIS
Dim FSOFolder As Object
FolderName = "C:\Users\320105013\Desktop\DXR\"
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.getfolder(FolderName)
Set FSOFiles = FSOFolder.Files ' CHANGE THIS
Set fso = CreateObject("Scripting.Filesystemobject")
startPath = "C:\Users\320105013\Desktop\DXR Test files\"
myName = ActiveSheet.Range("B3").Text ' Change as required to cell holding the folder title
If myName = vbNullString Then myName = "Testing"
Dim folderPathWithName As String
folderPathWithName = startPath & Application.PathSeparator & myName
If Dir(folderPathWithName, vbDirectory) = vbNullString Then
MkDir folderPathWithName
Else
MsgBox "Folder already exists"
Exit Sub
End If
ActiveWorkbook.FollowHyperlink startPath & myName
SourceFileName = "C:\Users\320105013\Desktop\DXR\" & (FSOFile)
DestinFileName = startPath & myName & "\"
For Each FSOFile In FSOFiles ' CHANGE THIS
If FSOFile Like "*.pdf" Then
FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
Next
End Sub
Okay I've changed it to below
but get error message "object doesn't support..." on line FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
Public Sub MyFileprojectTF()
Dim startPath As String
Dim myName As String
Dim SourceFileName As String, DestinFileName As String
Dim FSOFile As Object
Dim FSOFiles As Object
Dim FSOFolder As Object
FolderName = "C:\Users\320105013\Desktop\DXR\"
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.getfolder(FolderName)
Set FSOFiles = FSOFolder.Files
Set fso = CreateObject("Scripting.Filesystemobject")
startPath = "C:\Users\320105013\Desktop\DXR Test files\"
myName = ActiveSheet.Range("B3").Text ' Change as required to cell holding the folder title
If myName = vbNullString Then myName = "Testing"
Dim folderPathWithName As String
folderPathWithName = startPath & Application.PathSeparator & myName
If Dir(folderPathWithName, vbDirectory) = vbNullString Then
MkDir folderPathWithName
Else
MsgBox "Folder already exists"
Exit Sub
End If
ActiveWorkbook.FollowHyperlink startPath & myName
SourceFileName = "C:\Users\320105013\Desktop\DXR\"
DestinFileName = startPath & myName & "\"
For Each FSOFile In FSOFiles
If FSOFile Like "*.pdf" Then
FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
Next
End Sub
Move Files to a Folder
Using the MoveFile method is the simplest way to go.
The Code
Option Explicit
Public Sub MyFileprojectTF()
Const sFolderPath As String = "C:\Users\320105013\Desktop\DXR\"
Const dStartPath As String = "C:\Users\320105013\Desktop\DXR Test files\"
Const ExtensionPattern As String = "*.pdf"
Dim pSep As String: pSep = Application.PathSeparator
Dim wb As Workbook: Set wb = ThisWorkbook
Dim dFolderName As String
Dim dFolderPath As String
dFolderName = wb.Worksheets("Sheet1").Range("B3").Value
If dFolderName = vbNullString Then
dFolderName = "Testing"
End If
dFolderPath = dStartPath & pSep & dFolderName
If Dir(dFolderPath, vbDirectory) = vbNullString Then
If Dir(sFolderPath & pSep & ExtensionPattern) <> vbNullString Then
MkDir dFolderPath
With CreateObject("Scripting.FileSystemObject")
.MoveFile Source:=sFolderPath & pSep & ExtensionPattern, _
Destination:=dFolderPath
wb.FollowHyperlink dFolderPath
End With
Else
MsgBox "No matching files found in folder '" & sFolderPath & "'."
End If
Else
MsgBox "Folder '" & dFolderPath & "' already exists"
End If
End Sub
Related
I need to look in a specific folder and find the last file saved and move(or copy) to an other folder using VBA.
by finding the file i'm using:
Private Function fFindLastFile()
'Call GetFolder
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim myFolder As Object
Set myFolder = fso.GetFolder("D:\SF\C0T460A220000042\")
'Set myFolder = fso.GetFolder(GetFolder)
Dim myFile As Object
Set myFile = myFolder.Files.Item(myFolder.Files.Count) '<----- this is where i get a debug nr 5, unknown procedure or argument
MsgBox myFile.Name & " was last modified on " & myFile.DateLastModified
End Function
I don not have the name or type of the file that i'm looking for, but i just downloaded it from a known URL.
do you have any ideas what i'm doing wrong?
Last Modified File (FileSystemObject)
Option Explicit
Private Sub CopyLastFile()
Const sFolderPath As String = "D:\SF\C0T460A220000042\"
Const dFolderPath As String = "C:\Test\" ' adjust!
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim fsoFolder As Object: Set fsoFolder = fso.GetFolder(sFolderPath)
Dim fsoFile As Object, fName As String, fDate As Date
For Each fsoFile In fsoFolder.Files
If fsoFile.DateLastModified > fDate Then
fName = fsoFile.Name
fDate = fsoFile.DateLastModified
End If
Next fsoFile
If Len(fName) > 0 Then
fso.CopyFile sFolderPath & fName, dFolderPath, True
'fso.MoveFile sFolderPath & fName, dFolderPath, True
MsgBox "File Name: " & fName & vbLf & "Last modified: " & fDate, _
vbInformation, "Last Modified File"
Else
MsgBox "No file found.", vbExclamation, "Last Modified File"
End If
End Sub
I have a code which can transfer the Excel files from one folder to another but i would like to update the code so that it can move all the files (.xml, .txt, .pdf, etc.) from one folder to another.
Sub MoveFiles()
Dim sourceFolderPath As String, destinationFolderPath As String
Dim FSO As Object, sourceFolder As Object, file As Object
Dim fileName As String, sourceFilePath As String, destinationFilePath As String
Application.ScreenUpdating = False
sourceFolderPath = "E:\Source"
destinationFolderPath = "E:\Destination"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFolder = FSO.GetFolder(sourceFolderPath)
For Each file In sourceFolder.Files
fileName = file.Name
If InStr(fileName, ".xlsx") Then ' Only xlsx files will be moved
sourceFilePath = file.Path
destinationFilePath = destinationFolderPath & "\" & fileName
FSO.MoveFile Source:=sourceFilePath, Destination:=destinationFilePath
End If ' If InStr(sourceFileName, ".xlsx") Then' Only xlsx files will be moved
Next
'Don't need set file to nothing because it is initialized in for each loop
'and after this loop is automatically set to Nothing
Set sourceFolder = Nothing
Set FSO = Nothing
End Sub
can you please help
Move Files Using MoveFile
You would get greater control of things by using CopyFile and DeleteFile instead of MoveFile.
Using Dir, FileCopy, and Kill, instead of the FileSystemObject object and its methods, would make it simpler and also faster.
Option Explicit
Sub MoveFilesTEST()
Const sFolderPath As String = "E:\Source"
Const dFolderPath As String = "E:\Destination"
Const FilePattern As String = "*.*"
MoveFiles sFolderPath, dFolderPath, FilePattern
End Sub
Sub MoveFiles( _
ByVal SourceFolderPath As String, _
ByVal DestinationFolderPath As String, _
Optional ByVal FilePattern As String = "*.*")
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(SourceFolderPath) Then
MsgBox "The source folder path '" & SourceFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
If Not fso.FolderExists(DestinationFolderPath) Then
MsgBox "The destination folder path '" & DestinationFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
Dim apSep As String: apSep = Application.PathSeparator
Dim sPath As String: sPath = SourceFolderPath
If Left(sPath, 1) <> apSep Then sPath = sPath & apSep
Dim sFolder As Object: Set sFolder = fso.GetFolder(sPath)
If sFolder.Files.Count = 0 Then
MsgBox "There are no files in the source folder '" & sPath & "'.", _
vbExclamation
Exit Sub
End If
Dim dPath As String: dPath = DestinationFolderPath
If Left(dPath, 1) <> apSep Then dPath = dPath & apSep
Dim dFolder As Object: Set dFolder = fso.GetFolder(dPath)
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim sFile As Object
Dim dFilePath As String
Dim ErrNum As Long
Dim MovedCount As Long
Dim NotMovedCount As Long
For Each sFile In sFolder.Files
dFilePath = dPath & sFile.Name
If fso.FileExists(dFilePath) Then
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
Else
On Error Resume Next
fso.MoveFile sFile.Path, dFilePath
ErrNum = Err.Number
' e.g. 'Run-time error '70': Permission denied' e.g.
' when the file is open in Excel
On Error GoTo 0
If ErrNum = 0 Then
MovedCount = MovedCount + 1
Else
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
End If
End If
Next sFile
Dim Msg As String
Msg = "Files moved: " & MovedCount & "(" & NotMovedCount + MovedCount & ")"
If NotMovedCount > 0 Then
Msg = Msg & vbLf & "Files not moved:" & NotMovedCount & "(" _
& NotMovedCount + MovedCount & ")" & vbLf & vbLf _
& "The following files were not moved:" & vbLf _
& Join(dict.keys, vbLf)
End If
MsgBox Msg, IIf(NotMovedCount = 0, vbInformation, vbCritical)
End Sub
I found this code on another stack overflow post and it works well but the code prompts the user to select the file, can it be changed so that it automatically unzips all the files in the chosen directory?
Unzip folder with files to the chosen location
Sub Unzip()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=False)
If Fname = False Then
'Do nothing
Else
'Destination folder
DefPath = "C:\test\" ' Change to your path / variable
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
FileNameFolder = DefPath
' 'Delete all the files in the folder DefPath first if you want
' On Error Resume Next
' Kill DefPath & "*.*"
' On Error GoTo 0
'Extract the files into the Destination folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
MsgBox "You find the files here: " & FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
End Sub
Now with an added loop as brax is great to point out that I can use this but still doesn't solve the issue of the user being prompted for which file to open
Sub Unzip5()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim StrFile As String
StrFile = Dir("Z:\G Thang\Excel & VBA\Extract\*.zip")
Do While Len(StrFile) > 0
Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
MultiSelect:=False)
If Fname = False Then
'Do nothing
Else
'Destination folder
DefPath = "Z:\G Thang\Excel & VBA\Extract\" ' Change to your path / variable
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
FileNameFolder = DefPath
' 'Delete all the files in the folder DefPath first if you want
' On Error Resume Next
' Kill DefPath & "*.*"
' On Error GoTo 0
'Extract the files into the Destination folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
MsgBox "You find the files here: " & FileNameFolder
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
Loop
End Sub
ok, I'm getting it! But my new code loops through the same file and keeps unzipping that one, maybe I can move it into another directory when I've finished unzipping it and then move onto the next one, i'll post the code below.
Sub Unzip99File()
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim FileNameFolder As Variant
Dim DefPath As String
Dim StrFile As String
StrFile = Dir("Z:\G Thang\Excel & VBA\Extract\*.zip")
'Fname = ("*.zip")
Do While Len(StrFile) > 0
Fname = ("*.zip")
If Fname = False Then 'Fname
'Do nothing
Else
'Destination folder
DefPath = "Z:\G Thang\Excel & VBA\Extract\" ' Change to your path / variable
' If Right(DefPath, 1) <> "\" Then
' DefPath = DefPath & "\"
' End If
FileNameFolder = DefPath
' 'Delete all the files in the folder DefPath first if you want
' On Error Resume Next
' Kill DefPath & "*.*"
' On Error GoTo 0
'Extract the files into the Destination folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(DefPath & StrFile).items
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
End If
Loop
End Sub
I want to copy specific file type(*.SLDDRW) from source to destination,in destination path we have lots of folders and sub-folders .in below code i am trying to walk on any sub folders but unfortunately it didn't work and didn't walk all sub-folders S.O can help me?
Sub copy_specific_files_in_folder()
Dim FSO As Object
Dim sourcePath As String
Dim destinationPath As String
Dim fileExtn As String
sourcePath = "C:\Users\6\"
destinationPath = "C:\Users\"
fileExtn = "*.SLDDRW"
If Right (sourcePath, 1) <> "\" Then
sourcePath = sourcePath & "\"
End If
Set FSO = CreateObject ("scripting.filesystemobject")
If FSO.FolderExists(sourcepath) = False Then
MsgBox sourcePath & " does not exist"
Exit Sub
End If
FSO.CopyFile Source:=sourcePath & fileExtn, Destination :=destinationPath
copy_files_from_subfolders
MsgBox "Your files have been copied from the sub-folders of " & sourcePath
End sub
sub copy_files_from_subfolders()
Dim FSO AS Object , fld As Object
Dim fsoFile As Object
Dim fsoFol As Object
sourcePath = "C:\Users\6\"
targetPath = "C:\Users\"
If Right (sourcePath , 1) <> "\" then sourcePath = sourcePath & "\"
Set FSO = createObject("Scripting.FileSystemObject")
Set fld = FSO.getFolder(sourcePath)
If FSO.FolderExists(fld) Then
For Each fsoFol In FSO.GetFolder(sourcePath).SubFolders
For Each fsoFile In fsoFol.Files
If Right (fsoFile, 6) = "sldprt" Then
fsoFile.Copy targetPath
End If
Next
Next
End If
Here's a function that will recursively search a folder and all subfolders for a specific extension and then copy found files to a specified destination:
Sub SearchFoldersAndCopy(ByVal arg_sFolderPath As String, _
ByVal arg_sDestinationFolder As String, _
ByVal arg_sExtension As String)
Dim oFSO As Object
Dim oFolder As Object
Dim oSubFolder As Object
Dim sTest As String
'Test if FolderPath exists
sTest = Dir(arg_sFolderPath, vbDirectory)
If Len(sTest) = 0 Then
MsgBox "Specified folder [" & arg_sFolderPath & "] doesn't exist. Please check spelling or create the directory."
Exit Sub
End If
'Test if Destination exists
sTest = Dir(arg_sDestinationFolder, vbDirectory)
If Len(sTest) = 0 Then
MsgBox "Specified destination [" & arg_sDestinationFolder & "] doesn't exist. Please check spelling or create the directory."
Exit Sub
End If
'FolderPath and Destination both exist, proceed with search and copy
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(arg_sFolderPath)
'Test if any files with the Extension exist in directory and copy if one or more found
sTest = Dir(oFolder.Path & Application.PathSeparator & "*." & arg_sExtension)
If Len(sTest) > 0 Then oFSO.copyfile oFolder.Path & Application.PathSeparator & "*." & arg_sExtension, arg_sDestinationFolder
'Recursively search subfolders
For Each oSubFolder In oFolder.SubFolders
SearchFoldersAndCopy oSubFolder.Path, arg_sDestinationFolder, arg_sExtension
Next oSubFolder
End Sub
Here's an example of how to call it:
Sub tgr()
Dim sStartFolder As String
Dim sDestination As String
Dim sExtension As String
sStartFolder = "C:\Test"
sDestination = "C:\Output\" '<-- The ending \ may be required on some systems
sExtension = "SLDDRW"
SearchFoldersAndCopy sStartFolder, sDestination, sExtension
End Sub
Trying to use fso technique to copy from source folder C:\ ( V) to target folder C:(All) but running code give message runtime error 53. file not found
What I am trying to achieve is to copy all xlsx file from source folder C:\ V which contains also other file extension pdf, csv, txt, word..
All xlsx will be copied to folder C:\ALL,
Getting runtime error on this line below
****FSO.CopyFile Source:=sourcePath & fileExtn, Destination:=destinationPath****
Sub copy_specific_files_in_folder()
Dim FSO As Object
Dim sourcePath As String
Dim destinationPath As String
Dim fileExtn As String
sourcePath = "c:\V"
destinationPath = "c:\all\"
fileExtn = " * .xlsx"
If Right(sourcePath, 1) <> "\" Then
sourcePath = sourcePath & "\"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(sourcePath) = False Then
MsgBox sourcePath & " does not exit"
Exit Sub
End If
If FSO.FolderExists(destinationPath) = False Then
MsgBox destinationPath & " does not exit"
Exit Sub
End If
FSO.CopyFile Source:=sourcePath & fileExtn, Destination:=destinationPath
copy_files_from_subfolders
MsgBox "your files have been copied from subfolders of " & sourcePath & "to" & destinationPath
End Sub
Sub copy_files_from_subfolders()
Dim FSO As Object, fld As Object
Dim fsoFile As Object
Dim fsoFol As Object
sourcePath = "c:\V"
targetpath = "c:\all\"
If Right(sourcePath, 1) <> “ \ ” Then sourcePath = sourcePath & “ \ ”
Set FSO = CreateObject(“scripting.filesystemobject”)
Set fld = FSO.GetFolder(sourcePath)
If FSO.FolderExists(fld) Then
For Each fsoFol In FSO.GetFolder(sourcePath).SubFolders
For Each fsoFile In fsoFol.Files
If Right(fsoFile, 4) = “xlsx” Then
fsoFile.Copy targetpath
End If
Next
Next
End If
End Sub
Hi change fileExtn = " * .xlsx" to fileExtn = "*.xlsx" and that should fix your issue.
EDIT
The code below should fix your other sub procedure.
Sub copy_files_from_subfolders()
Dim FSO As Object, fld As Object
Dim fsoFile As Object
Dim fsoFol As Object
sourcePath = "c:\V"
targetpath = "c:\all\"
If Right(sourcePath, 1) <> "\" Then sourcePath = sourcePath & "\"
Set FSO = CreateObject("scripting.filesystemobject")
Set fld = FSO.GetFolder(sourcePath)
If FSO.FolderExists(fld) Then
For Each fsoFol In FSO.GetFolder(sourcePath).SubFolders
For Each fsoFile In fsoFol.Files
If Right(fsoFile, 4) = “xlsx” Then
fsoFile.Copy targetpath
End If
Next
Next
End If
End Sub
I have checked "Sub copy_specific_files_in_foldera()" works, it copies all files in main directory from c:\v to c:\all but in applying your edit . I get compile error message variable not defined sourcePath . the "Sub copy_files_from_subfolders()" in yellow.
Sub copy_specific_files_in_foldera()
Dim FSO As Object
Dim sourcePath As String
Dim destinationPath As String
Dim fileExtn As String
sourcePath = "c:\V"
destinationPath = "c:\all\"
fileExtn = "*.xlsx"
If Right(sourcePath, 1) <> "\" Then
sourcePath = sourcePath & "\"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(sourcePath) = False Then
MsgBox sourcePath & " does not exit"
Exit Sub
End If
If FSO.FolderExists(destinationPath) = False Then
MsgBox destinationPath & " does not exit"
Exit Sub
End If
FSO.CopyFile Source:=sourcePath & fileExtn, Destination:=destinationPath
'copy_files_from_subfolders 'suspend'
MsgBox "your files have been copied from subfolders of " & sourcePath & "to" & destinationPath
End Sub
Generally too much hard-coding in the functions/subs.
Keep the variables as inputs:
I have added a Reference to Microsoft.Scripting.Runtime
Sub CopyFiles(extension As String, sourceFolder As String, targetFolder As String, recursive As Boolean)
Dim fso As New FileSystemObject
Dim src As folder, dest As folder
Set src = fso.GetFolder(sourceFolder)
Set dest = fso.GetFolder(targetFolder)
Dim srcFile As File
For Each srcFile In src.Files
Dim srcFilepath As String
srcFilepath = srcFile.Path
If Right(srcFilepath, Len(srcFilepath) - InStrRev(srcFilepath, ".") + 1) = extension Then 'extension includes the "."
srcFile.Copy targetFolder, True 'I set Overwrite to True
End If
Next srcFile
If recursive Then 'If recursive is True then will go through all subfolders recursively
Dim subDir As folder
For Each subDir In src.SubFolders
CopyFiles extension, subDir.Path, targetFolder, True
Next subDir
End If
End Sub
Sub testCopy()
CopyFiles ".xlsm", "C:\Source", "C:\Destination\", True
End Sub