• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
    • Password Reset
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member
You are here: Home
Lost password?
sp_Search
Advanced Search|Last Search Results
Advanced Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search

Please confirm you want to mark all posts read

Mark all topics read

sp_MobileMenu Actions
Actions
sp_LogInOut
Log In
sp_Search

Search Forums

sp_RankInfo
Ranks Information
Avatar

New/Updated Topics

General Excel Questions & Answers

  Data Validation with unique values

  Quartile reporting

  Create calendar with slicers or vba ?

  Sick leave periods in one cell

  removing pesky hidden xml sheets in a workbook

  Excel Is Running Slow

VBA & Macros

  VBA Update the body from a template email

Power Query

  Running total in power query

  Removing columns in Power BI source file

  Opening several PDFs from a Sharepoint site, and validating …

  Using Table.ReplaceValue with Text.Combine to do an in place…

  Converting Values from positive to Negative in Power Query

Power Pivot

   Problem in Runing Total using Pivot Table

Xtreme Pivot Tables

  Structuring data to drive pivot tables.

Select Forum

  Rules and Guides

Forum Rules and Guides

  Public Forums - For Registered Users

General Excel Questions & Answers

Dashboards & Charts

VBA & Macros

Power Query

Power Pivot

  Course Members Only

Excel Dashboards

Power Query

Power Pivot

Xtreme Pivot Tables

Excel for Decision Making

Excel for Finance

Power BI

Excel

Word

Outlook

Excel Expert

Excel for Customer Service Professionals

Excel Analysis Toolpak

Excel Tables

Excel for Operations Management

Financial Modelling

Advanced Excel Formulas

Pivot Tables Quick Start

ForumsVBA & Macros
sp_TopicIcon
Macro to copy specific workbooks from sub-folders
Avatar
Howard Cohen
Posts: 48
Level 0
August 20, 2020 - 3:23 am

1

I have several files in sub folders on a network "\\account\man\

The sub folders are for eg "\\account\man\BR1\

"\\account\admin\BR2\

"\\account\admin\sammy\

Etc

I would like all files that contain "Template 2020.xlsm to be copied from the sub-folders for eg BR Sales Report template 2020.xlsm to C:\Sales Reports\

It would be appreciated if someone could amend my code

Sub CopyWorkbookstoanotherFolder()

'Declare Variables
Dim FSO
Dim sFile As String
Dim sSFolder As String
Dim sDFolder As String

'This is Your File Name which you want to Copy
sFile = "*Template.2020.xlsm*"

'Change to match the source folder path
sSFolder = "\\account\man\"

'Change to match the destination folder path
sDFolder = "C:\Sales Reports\"

'Create Object
Set FSO = CreateObject("Scripting.FileSystemObject")

'Checking If File Is Located in the Source Folder
If Not FSO.FileExists(sSFolder & sFile) Then
    MsgBox "Specified File Not Found", vbInformation, "Not Found"
   
'Copying If the Same File is Not Located in the Destination Folder
ElseIf Not FSO.FileExists(sDFolder & sFile) Then
    FSO.CopyFile (sSFolder & sFile), sDFolder, True
    MsgBox "Specified File Copied Successfully", vbInformation, "Done!"
Else
    MsgBox "Specified File Already Exists In The Destination Folder", vbExclamation, "File Already Exists"
End If

End Sub

sp_AnswersTopicSeeAnswer
Avatar
Catalin Bombea
Iasi, Romania
Posts: 1810
Level 10
August 21, 2020 - 4:23 pm

2

Hi Howard,

You can also loop through the main folder subfolders:

Dim SbFld as object, FileObject as Object

For each SbFld in fso.GetFolder(sSFolder).SubFolders 'loop through subfolders

    For each FileObject in fso.GetFolder(SbFld).Files 'loop through files in each subfolder

           If FileObject.Name like "*Template*2020*xlsm" then

           'copy it, we found a file matching the template

           End IF    

   Next FileObject

Next SbFld

Avatar
Howard Cohen
Posts: 48
Level 0
September 25, 2020 - 1:38 pm

3

Sorry for only getting back to you now, but but been incredibly busy

 

I incoroprated your code with mine and get a compile error "Next without for"

 

Kindly amend code below

 

Sub sbCopyingAFile()

'Declare Variables
Dim FSO
Dim sFile As String
Dim sSFolder As String
Dim sDFolder As String
Dim SbFld As Object
Dim FileObject As Object
For Each SbFld In FSO.GetFolder(sSFolder).SubFolders 'loop through subfolders

For Each FileObject In FSO.GetFolder(SbFld).Files 'loop through files in each subfolder
If FileObject.Name Like "*Template*2020*xlsm" Then

'This is Your File Name which you want to Copy
'sFile = "*Template.2020.xlsm*"

'Change to match the source folder path

sSFolder = "\\account\man\"

'Change to match the destination folder path
sDFolder = "C:\Sales Reports\"

'Create Object
Set FSO = CreateObject("Scripting.FileSystemObject")

'Checking If File Is Located in the Source Folder
If Not FSO.FileExists(sSFolder & sFile) Then
MsgBox "Specified File Not Found", vbInformation, "Not Found"

'Copying If the Same File is Not Located in the Destination Folder
ElseIf Not FSO.FileExists(sDFolder & sFile) Then
FSO.CopyFile (sSFolder & sFile), sDFolder, True
MsgBox "Specified File Copied Successfully", vbInformation, "Done!"
Else
MsgBox "Specified File Already Exists In The Destination Folder", vbExclamation, "File Already Exists"
End If
Next FileObject

Next SbFld
End Sub 

Avatar
Catalin Bombea
Iasi, Romania
Posts: 1810
Level 10
September 25, 2020 - 5:20 pm

4

There are many more issues in your code.

You have 2 lines with If...Then, but only 1 End If closing line.

Second issue:
move static parameters like sfile, sSFolder, sDFolder outside the loop, before loops. Makes no sense to set these parameters within loops, they will be set at every file found in those subfolders.

Another issue:

In order to use the file system object with FSO.GetFolder(sSFolder).SubFolders, it's a good idea to... create the object before using it, will not work otherwise. Before the loops, you have to create the FSO object.

 

And another one:

'Checking If File Is Located in the Source Folder
If Not FSO.FileExists(sSFolder & sFile) Then

This check is a nonsense. Because we use For Each FileObject In FSO.GetFolder(SbFld).Files, this means that we deal only with EXISTING files, checking an EXISTING file if it exists is simply redundant.

I can only guess that what you was trying to do is to see if the file naming structure corresponds to your convention sFile.
The code already does that in this line: If FileObject.Name Like "*Template*2020*xlsm" Then

Sub sbCopyingAFile()
'Declare Variables
Dim FSO
Dim sFile As String
Dim sSFolder As String
Dim sDFolder As String
Dim SbFld As Object
Dim FileObject As Object

'This is Your File Name which you want to Copy
sFile = "*Template*2020.xlsm*"
'Change to match the source folder path
sSFolder = "\\account\man\"
'Change to match the destination folder path
sDFolder = "C:\Sales Reports\"
'Create Object
Set FSO = CreateObject("Scripting.FileSystemObject")

For Each SbFld In FSO.GetFolder(sSFolder).SubFolders 'loop through subfolders
    For Each FileObject In FSO.GetFolder(SbFld).Files 'loop through files in each subfolder
        If FileObject.Name Like sFile Then
            'Copying If the Same File is Not Located in the Destination Folder
            If Not FSO.FileExists(sDFolder & FileObject.Name) Then
                FSO.CopyFile (FileObject.Path), sDFolder & FileObject.Name, True
                MsgBox "Specified File Copied Successfully", vbInformation, "Done!"
            Else
                MsgBox "Specified File Already Exists In The Destination Folder", vbExclamation, "File Already Exists"
            End If
        End If
    Next FileObject
Next SbFld
End Sub

Avatar
Howard Cohen
Posts: 48
Level 0
September 25, 2020 - 8:39 pm

5

Hi Catalin

 

This is beyond my VBA programming skills.

 

I am trying to copy all files within the network folder "\\account\man\" as well as its sub-folders that contain ""*Template*2020.xlsm*" for e.g. BR1 Sothern template Sales 2020.xlsm, BR2 Sothern template Sales 2020.xlsm etc and copy these to  "C:\Sales Reports\"

 

It would be appreciated if you would kindly provide me with the code to do this

Avatar
Philip Treacy
Posts: 1517
Level 10
October 6, 2020 - 9:51 am

6

Hi Howard,

It's much easier to do this kind of thing directly in the command line.  Writing VBA to call FSO is just using the Windows Shell/Command Line anyway and way more work than it needs to be.

Start a Command Prompt and all you need is a line like this

xcopy "x:\man\*template*2020.xlsm" "c:\Sales Reports" /S /I /C

Where x:\man is a drive mapping to your \\account\man folder. 

I'm assuming you have the drive mapped? If not then using the UNC format "\\account\man\*template*2020.xlsm" should also work.

If you need to copy files periodically you can either place this line of code into a batch file or use VBA to call a Shell command

VBA Shell Function

Please read the XCOPY doco to understand how it works

https://docs.microsoft.com/en-.....ands/xcopy

Regards

Phil

sp_AnswersTopicAnswer
Avatar
Catalin Bombea
Iasi, Romania
Posts: 1810
Level 10
October 6, 2020 - 2:45 pm

7

It would be appreciated if you would kindly provide me with the code to do this

Hi Howard,

That's exactly what I did, you have in the previous message the corrected code, all you had to do is to paste it into your file and run it.

Avatar
Howard Cohen
Posts: 48
Level 0
October 6, 2020 - 9:35 pm

8

Many Thanks for your help

Forum Timezone:
Australia/Brisbane
Most Users Ever Online: 245
Currently Online: RAQUEL ACION, Dana Friedt, Nada Perovic
Guest(s) 10
Currently Browsing this Page:
1 Guest(s)

Devices in use: Desktop (8), Phone (5)

Forum Stats:
Groups: 3
Forums: 24
Topics: 6218
Posts: 27266
Member Stats:
Guest Posters: 49
Members: 31901
Moderators: 3
Admins: 4
© Simple:Press

Sidebar

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk - For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved. Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.