Another post by me

SFPCFS

New Member
Joined
Feb 7, 2014
Messages
40
Firstly a massive thank you for the help from this forum,

I've been handed the following today as well, which is a little out of my zone, but I am trying to learn it.

I have the following code in a sheet

Code:
[INDENT=2]Option Explicit</SPAN>
Sub copySheet()</SPAN>
    Dim ChangeRequestBooks() As Workbook</SPAN>
           Application.ScreenUpdating = False</SPAN>
   
    ChangeRequestBooks = openFiles()    </SPAN>
    If ChangeRequestBooks(0) Is Nothing Then</SPAN>
              MsgBox "Update Cancelled"</SPAN>
    Else</SPAN>
              processFiles ChangeRequestBooks</SPAN>
        MsgBox "Update Complete"</SPAN>
    End If</SPAN>
   
        Application.ScreenUpdating = True</SPAN>
       End Sub</SPAN>
' Prompts the user for a list of files and returns a referece (in an array) to all the files.</SPAN>
' Opens all the files ready to be processed.</SPAN>
Function openFiles() As Workbook()</SPAN>
    Dim Wb() As Workbook</SPAN>
    Dim i As Long, c As Long</SPAN>
    Dim FilesToOpen As Variant</SPAN>
   
    ' tell the user what we want them to do</SPAN>
    MsgBox "Select workbook(s) to copy.", vbApplicationModal</SPAN>
   
    ' note that if you want to have the open dialogue start in a specific folder then</SPAN>
    ' use ChDrive and ChDir (uncoment following section and update it to the correct path)</SPAN>
    'ChDrive "H:"    ' note that if used on multiple systems the drive letter isn't always the same</SPAN>
    'ChDir "H:\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Financial Risk MI Change\Change Request Forms Recived"    ' is the folder spelt wrong? Recived or Received?</SPAN>
    ' prompt the user with an open dialog</SPAN>
    FilesToOpen = Application.GetOpenFilename(FileFilter:="Microsoft Excel (*.xl*),*.xl*", Title:="Please select all change request files required", MultiSelect:=True)</SPAN>
   
       If Not IsArray(FilesToOpen) Then</SPAN>
        ReDim openFiles(0)  </SPAN>
        Exit Function  </SPAN>
    End If</SPAN>
   
           For i = LBound(FilesToOpen) To UBound(FilesToOpen)</SPAN>
        ReDim Preserve Wb(c) ' need to create a space in the array for the file we're about to open</SPAN>
        Set Wb(c) = Workbooks.Open(FileName:=FilesToOpen(i), UpdateLinks:=False, ReadOnly:=True)</SPAN>
            c = c + 1</SPAN>
    Next i
[INDENT=2]openFiles = Wb</SPAN>
End Function</SPAN>
Private Sub processFiles(Wb() As Workbook)</SPAN>
    Dim i As Long</SPAN>
    Dim ws As Worksheet</SPAN>
    Dim SourceRange As range, TargetRange As range</SPAN>
   
        Set ws = ThisWorkbook.Worksheets("SummarySheet")</SPAN>
           Set TargetRange = ws.Cells(ws.Cells.Rows.Count, 2)</SPAN>
           Set TargetRange = TargetRange.End(xlUp)</SPAN>
           Set TargetRange = TargetRange.Cells(2, 1)       </SPAN>
   
    For i = LBound(Wb) To UBound(Wb)</SPAN>
        With Wb(i) </SPAN>
            If .Worksheets.Count >= 2 Then</SPAN>
               Set ws = .Worksheets(2)  </SPAN>
                Set SourceRange = ws.Cells(2, 2) </SPAN>
                Set SourceRange = ws.range(SourceRange, SourceRange.End(xlToRight))</SPAN>
                    SourceRange.Copy</SPAN>
                TargetRange.PasteSpecial xlPasteValues</SPAN>
                Application.CutCopyMode = False</SPAN>
                Set TargetRange = TargetRange.Cells(2, 1)</SPAN>
            Else</SPAN>
                MsgBox "Filename: '" & .Name & "', is missing the sheet we need. Skipping it."</SPAN>
            End If</SPAN>
           
            ' close the file we've finished with it now</SPAN>
            .Close SaveChanges:=False    ' false to not attempt to save changes (and not prompt the user for it)</SPAN>
        End With</SPAN>
    Next i</SPAN>
   
    ' by this point all the files that were opened should be closed and we should be looking at the completed SummarySheet table</SPAN>
End Sub</SPAN>
[/INDENT]
</SPAN>[/INDENT]
Into this I need to add that the sheets the user selects are saved as a PDF to a folder that is named after the cell in column a that is the row it is appended to, in the same location as this log is kept

I've recorded this -


Code:
[INDENT=2]Option Explicit</SPAN>
Sub Macro1()</SPAN>
'</SPAN>
' Macro1 Macro</SPAN>
'</SPAN>
'</SPAN>
    ChDir _</SPAN>
        "H:\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Financial Risk MI Change\Change Request Forms Recived"</SPAN>
    Workbooks.Open Filename:= _</SPAN>
        "Same as above with filename"</SPAN>
    Range("H10:J10").Select</SPAN>
    ChDir _</SPAN>
        "Same as above but with the filename on were its being saved"</SPAN>
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _</SPAN>
        "H:\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Financial Risk MI Change\Change Request Forms Recived\FS & MI 2\Change Request Form.pdf" _</SPAN>
        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _</SPAN>
        :=False, OpenAfterPublish:=True</SPAN>
    Range("Q26").Select</SPAN>
    ActiveWindow.Close</SPAN>
End Sub</SPAN>
[/INDENT]

I can recognize the save as section

I'll be putting the publish to false as there could be multiple uploads at the same time so it would slow the process down a little I think.

Could you help me in terms of how I would go about this?

Fully appreciate this is big ask or at least feels like for me I’m afraid

Thank you for any help</SPAN>


And apologies for missing one of the most important rules
</SPAN>​
</SPAN>
 
In a effort to maybe make it a little clear what I'm trying to do I've broken down what I ideally need to be able to do

1 - The current code completes the upload function with out any issues at all, and from any area were these templates are saved.

2 - I need to add in the following abilty to the code

2.1 - In the same folder :)\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log) it creates a folder which uses the the cell in colum A, on the row were the data is uploaded to to name the folder

2.2 - It then saves a PDF of the first sheet in that folder of the request form it is uploading (The PDF should ba of Worksheet1, but the data upload is from Worksheet2) into this folder and simply names it Request Form.

It needs to do this for each sheet it uploads.

I have not included the drive letter as previosuly mentioned this is not the same for all users

And the code at the top of this thread in post 1 is the code into which I need to fit this adaption in to.

Hope this makes more sense?
 
Upvote 0

Excel Facts

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
Would I need to use mkdir in this some were?

I'm trying to solve the problem as well as trying to learn more about this as I go to understand what I'm dealing with.

If I understand I can use MkDir to create the folder, but it seems to rely on a fixed file path and drive letter - which on a network is not always the case for myself.

I do have a fixed location path, the only variable is the drive letter.

Would I be on the right lines of thinking that this + xenous code would complete the function I'm looking for?

for example in a very heath robinson style and in nows proper code

after -
Code:
Set TargetRange = TargetRange.Cells(2, 1)

would it be along the lines of

MkDir <File Path," TargetRange.Cells(1,1)

Then xenous?

I know its not right but I'm thinking its on the right path?

Hope we can figure this out
 
Upvote 0
2.1 - In the same folder :)\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log) it creates a folder which uses the the cell in colum A, on the row were the data is uploaded to to name the folder

2.2 - It then saves a PDF of the first sheet in that folder of the request form it is uploading (The PDF should ba of Worksheet1, but the data upload is from Worksheet2) into this folder and simply names it Request Form.

From my post # 2, change:
Code:
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=TargetRange.Cells(1,1), Quality:=xlQualityStandard, _
                                        IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

Instead this:
Code:
    [COLOR="#B22222"]myNewFolderName [/COLOR]= ":\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log\" & TargetRange.Cells(1,1)
    CreateObject("Scripting.FileSystemObject").CreateFolder [COLOR="#B22222"]myNewFolderName[/COLOR]
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=[COLOR="#B22222"]myNewFolderName [/COLOR]& "\Request Form", Quality:=xlQualityStandard, _
     IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

You will have to dim a variable called myNewFolderName. Also the file folder you provided (:\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log\) is not a valid path so you need to fix that. This code will *crash* if anything goes wrong - the folder already exists, for example, or it is an invalid path.

You should be using UNC file path naming convention if possible, to avoid drive letters.
UNC Path Names in Windows - Universal Naming Convention

I'm not sure you should be writing code for shared use if you are just learning VBA for the first time. You are in danger of having a lot of people aggravated with you when things go wrong. You might want to consider getting a consultant for the job.
 
Upvote 0
Thanks for that

If I've got this right I can add this in with the dim section of the code, then update the section you intially provided.

there are drive names as such, but its the actually letter at the start that is different for the users

in my drive areas it reads as <NAME>on '<SERVER(SERVER)' letter.

Is there a way to get the code to put the drive letter in? or maybe the user to select it prior to up loading the sheets?

I've found the activieworkbook.path code which seems to specify the location the sheet is saved in - would this be able to help the code and stop it from crashing?

So for example?

current

Code:
  [COLOR=#b22222]myNewFolderName [/COLOR]= ":\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log\" & TargetRange.Cells(1,1)
    CreateObject("Scripting.FileSystemObject").CreateFolder [COLOR=#b22222]myNewFolderName[/COLOR]
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=[COLOR=#b22222]myNewFolderName [/COLOR]& "\Request Form", Quality:=xlQualityStandard, _
     IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

poss?

Code:
  [COLOR=#b22222]myNewFolderName [/COLOR]= 'Activeworkbook.path' & TargetRange.Cells(1,1)
    CreateObject("Scripting.FileSystemObject").CreateFolder [COLOR=#b22222]myNewFolderName[/COLOR]
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=[COLOR=#b22222]myNewFolderName [/COLOR]& "\Request Form", Quality:=xlQualityStandard, _
     IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

In regards to consultants etc the sheet is for 3/4 users and currently is managed locally by each one so there is not much impact at the minute and its one of my objectives to improve my learning.

Thank you for the assistance so far
 
Upvote 0
Update

Been working on this virtually all day to learn it and get it working and I've made some progress

So I've added the following to my dims

Code:
 Dim FNR As range
    Dim MNFPath As String
    Dim myNewFolderName As String

And put the following in - I'll update why I've comented out some following this

Code:
MNFPath = "[URL="file://\\mnas01\accdata2\1"]\\mnas01\accdata2\1[/URL]. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log\"
                 myNewFolderName = MNFPath & "Test"
                    CreateObject("Scripting.FileSystemObject").CreateFolder myNewFolderName
                                'ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myNewFolderName & "\Request Form", Quality:=xlQualityStandard,
                    'IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

Now this will create the folder test in the File path correctly and past the data - however I get a error when i enable the pdf side of things (doesn't seem to like ws. )

I'm also unable to get it to take the cell referance as the folder name - It'll give me test fine, but when I put in the target range line it just gives me target range (cell 1, 1) as the file name

So I'm getting closer - and as xenou mentioned I've utalised then unc style of calling to make it more flexiable and safer
 
Upvote 0
Now this will create the folder test in the File path correctly and past the data - however I get a error when i enable the pdf side of things (doesn't seem to like ws. )

I'm also unable to get it to take the cell referance as the folder name - It'll give me test fine, but when I put in the target range line it just gives me target range (cell 1, 1) as the file name

What you have done looks right, based on what you have in your last post. I guess you should post the complete code as it stands now - maybe there's something there in the "bigger picture" that we can fix.
 
Upvote 0
Code as it currently stands

Code:
Option Explicit</SPAN>
 
Sub copySheet()</SPAN>
    Dim ChangeRequestBooks() As Workbook</SPAN>
 
    Application.ScreenUpdating = False</SPAN>
   
    ChangeRequestBooks = openFiles()    </SPAN>
 
    If ChangeRequestBooks(0) Is Nothing Then</SPAN>
 
        MsgBox "Update Cancelled"</SPAN>
    Else</SPAN>
        processFiles ChangeRequestBooks</SPAN>
        MsgBox "Update Complete"</SPAN>
    End If</SPAN>
   
    Application.ScreenUpdating = True</SPAN>
End Sub</SPAN>
 
Function openFiles() As Workbook()</SPAN>
    Dim Wb() As Workbook</SPAN>
    Dim i As Long, c As Long</SPAN>
    Dim FilesToOpen As Variant</SPAN>
   
    MsgBox "Select workbook(s) to copy.", vbApplicationModal</SPAN>
   
    FilesToOpen = Application.GetOpenFilename(FileFilter:="Microsoft Excel (*.xl*),*.xl*", Title:="Please select all change request files required", MultiSelect:=True)</SPAN>
   
   
    If Not IsArray(FilesToOpen) Then</SPAN>
        ReDim openFiles(0)               </SPAN>
        Exit Function   </SPAN>
    End If</SPAN>
   
  
    For i = LBound(FilesToOpen) To UBound(FilesToOpen)</SPAN>
        ReDim Preserve Wb(c)</SPAN>
        Set Wb(c) = Workbooks.Open(Filename:=FilesToOpen(i), UpdateLinks:=False, ReadOnly:=True)</SPAN>
        c = c + 1 '</SPAN>
    Next i</SPAN>
   
    openFiles = Wb</SPAN>
End Function</SPAN>
 
Private Sub processFiles(Wb() As Workbook)</SPAN>
    Dim i As Long</SPAN>
    Dim ws As Worksheet</SPAN>
    Dim SourceRange As range, TargetRange As range, FNR As range</SPAN>
    Dim MNFPath As String</SPAN>
    Dim myNewFolderName As String</SPAN>
   
 
    Set ws = ThisWorkbook.Worksheets("SummarySheet")</SPAN>
    Set TargetRange = ws.Cells(ws.Cells.Rows.Count, 2)</SPAN>
    Set TargetRange = TargetRange.End(xlUp)</SPAN>
    Set TargetRange = TargetRange.Cells(2, 1)   </SPAN>
        'Set Filsave name value</SPAN>
 
     
   
    For i = LBound(Wb) To UBound(Wb)</SPAN>
        With Wb(i)  </SPAN>
           
           
            If .Worksheets.Count >= 2 Then</SPAN>
                Set ws = .Worksheets(2)   </SPAN>
                Set SourceRange = ws.Cells(2, 2)                    </SPAN>
                Set SourceRange = ws.range(SourceRange, SourceRange.End(xlToRight))</SPAN>
                SourceRange.Copy</SPAN>
                TargetRange.PasteSpecial xlPasteValues</SPAN>
                Application.CutCopyMode = False</SPAN>
                Set TargetRange = TargetRange.Cells(2, 1)</SPAN>
               
                 'FNR = TargetRange.Cells(1, -1).Value</SPAN>
                 MNFPath = "\\mnas01\accdata2\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log\"</SPAN>
                 myNewFolderName = MNFPath & "FNR"</SPAN>
                    CreateObject("Scripting.FileSystemObject").CreateFolder myNewFolderName</SPAN>
                                'ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myNewFolderName & "\Request Form", Quality:=xlQualityStandard,</SPAN>
                    'IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False</SPAN>
                   
                Else</SPAN>
                MsgBox "Filename: '" & .Name & "', is missing the sheet we need. Skipping it."</SPAN>
               
       
               
            End If</SPAN>
            .Close SaveChanges:=False    </SPAN>
        End With</SPAN>
    Next i</SPAN>
End Sub</SPAN>

I've tried to referance FNR to a cell but failled here

Thank you the help you've provided so far

Hopefully we are almost there with this?
 
Upvote 0
This has to be wrong. TargetRange is undefined when you try to use it:
Code:
Set ws = ThisWorkbook.Worksheets("SummarySheet")
    Set TargetRange = TargetRange.Cells(2, 1)

Maybe you mean (?):
Code:
Set ws = ThisWorkbook.Worksheets("SummarySheet")
    Set TargetRange = ws.Cells(2, 1)


This is bad:
Code:
            If .Worksheets.Count >= 2 Then
                Set ws = .Worksheets(2)

You are setting the ws variable again, but you are already using it as a reference to the SummarySheet. Do you mean to do this?

If so I would not have used it in the first place:
Code:
Set ws = ThisWorkbook.Worksheets("SummarySheet")
    Set TargetRange = ws.Cells(2, 1)
Instead use:
Code:
Set TargetRange = ThisWorkbook.Worksheets("SummarySheet").Cells(2, 1)
If not, then it's a problem.
 
Upvote 0
Hi

Thanks for the comments

In my understanding of the annotation wrttin around this (I had to take the green notes out due to the length constraints)

Looking a tthe points you raise - the comments I have that were written into the code are as follows

Code:
Set ws = ThisWorkbook.Worksheets("SummarySheet")
        ' note the use of 'ThisWorkbook', no matter which book is active this will always refer to the book that contains the code currently running
    Set TargetRange = ws.Cells(ws.Cells.Rows.Count, 2)
        ' by using the row count we avoid any problems if we're in compatibility mode or not, i.e. 65536 rows vs. 1048576
    Set TargetRange = TargetRange.End(xlUp)
        ' Target Range now points to the last filled row of the summary sheet (or the header)
        ' need to move it down one cell
    Set TargetRange = TargetRange.Cells(2, 1)   ' note that cell references are relative to the start point (base-1)
        'Set Filsave name value

The comment above the duplicated target cell range reads as follows
Code:
 ' make sure we move the target paste area on one ready for the next paste (if any)
                Set TargetRange = TargetRange.Cells(2, 1)

This the comments for copying the data from the request forms into the master log

Code:
' we now need to look at each change request file and pick up the data contained in the background sheet
    ' loop through each sheet
    For i = LBound(Wb) To UBound(Wb)
        With Wb(i)  ' saying 'With' stops us from having to type Wb(i) every time we need to refer to the workbook we're currently looking at
                    ' any time we want to refer to the workbook now we just start with the dot operator '.' instead
            
            ' we can only do the copy we want if we know the sheet we're looking for exists
            ' if there's only 1 sheet in the source book, it's probably not the right file so skip it
            If .Worksheets.Count >= 2 Then
                ' ideally we should do more testing of the source file before we try and copy from it, validate it is the file type intended
                
                Set ws = .Worksheets(2)   ' new use for Ws variable to refer to second worksheet (that's hidden)
                ' note you can look at the data in the hidden sheet without needing to make it visible
                
                ' find the data we want and get a range reference to it
                Set SourceRange = ws.Cells(2, 2) ' it's better to use index values to locate a cell, instead of the "A1" textual reference
                    ' it's used SheetRef.Cells(Row Number, Column Number) where the numbers start at 1, 1 for the top left corner of the sheet
                Set SourceRange = ws.range(SourceRange, SourceRange.End(xlToRight))
                    ' rather than use a fixed size area for the data, we define it by doing the VBA equivalent of Ctrl+Shift+Right Arrow
                    ' to discover the end point of the range we want (i.e. End(xlToRight)
                    ' the Range property takes the two arguments for the top left corner and bottom right corner of the are we want a reference to
                    
                ' now we can copy and paste the data across
                SourceRange.Copy
                TargetRange.PasteSpecial xlPasteValues
                Application.CutCopyMode = False
                    ' this turns off the copy area (marching ants border) so it doesn't prompt the user when we close the file

Hope this adds a little more informations - If I could add the whole code + its annotations I would do so, but it is very long and I think it exceeds the limits here?

I'll try in another post under this one - if its there it will show all comments as per the code
 
Upvote 0
Full code + comments held within

Code:
Option Explicit
' always put Option Explicit at the top of any module to force all variable to be declared
' this helps you avoid errors in code

Sub copySheet()
    Dim ChangeRequestBooks() As Workbook
        ' this is an array of workbooks, we can set up the code to handle more than one file in one go
    
    ' turns off screen updating to the user to avoid slowdown from drawing updates
    ' note that having screen updating off doesn't affect things like message boxes
    Application.ScreenUpdating = False
    
    ChangeRequestBooks = openFiles()    ' it is not necessary to use 'Call' these days in VBA, it's an archaic form of coding.
        ' openFiles (plural) now will allow the user to select multiple change requests and process all of them one after the other
        ' we pass off the processing of the files to a seperate procedure
    
    ' need to check if the user cancelled or not
    If ChangeRequestBooks(0) Is Nothing Then
        ' user pressed cancel, so do nothing
        MsgBox "Update Cancelled"
    Else
        ' otherwise process and close the files we opened already
        processFiles ChangeRequestBooks
        MsgBox "Update Complete"
    End If
    
    ' clean up
    Application.ScreenUpdating = True
        ' Excel will automatically turn screen updating back on again at the end of running code, but doesn't hurt to do it explicitly.
End Sub
' Prompts the user for a list of files and returns a referece (in an array) to all the files.
' Opens all the files ready to be processed.
Function openFiles() As Workbook()
    Dim Wb() As Workbook
    Dim i As Long, c As Long
    Dim FilesToOpen As Variant
    
    ' tell the user what we want them to do
    MsgBox "Select workbook(s) to copy.", vbApplicationModal
    
    ' note that if you want to have the open dialogue start in a specific folder then
    ' use ChDrive and ChDir (uncoment following section and update it to the correct path)
    'ChDrive "H:"    ' note that if used on multiple systems the drive letter isn't always the same
    'ChDir "H:\1. Finance Shared Services\FINANCE DATA & MI CHANGE\Financial Risk MI Change\Change Request Forms Recived"    ' is the folder spelt wrong? Recived or Received?
    ' prompt the user with an open dialog
    FilesToOpen = Application.GetOpenFilename(FileFilter:="Microsoft Excel (*.xl*),*.xl*", Title:="Please select all change request files required", MultiSelect:=True)
    
    ' we need to detect if the user pressed cancel and handle that appropriately
    
    If Not IsArray(FilesToOpen) Then
        ReDim openFiles(0)   ' while we aren't opening any files we need to pass back a value that has meaning to allow it to know we've cancelled
            ' in this case an array with a single value of 'Nothing' in it.
        Exit Function   ' we exit the function here, so none of the code after this is run
    End If
    
    ' FilesToOpen now contains an array of all the files selected (even if it's only one)
    
    ' note that at this point varible 'c' is zero
    
    ' loop through the files to open one by one
    For i = LBound(FilesToOpen) To UBound(FilesToOpen)
        ReDim Preserve Wb(c) ' need to create a space in the array for the file we're about to open
        Set Wb(c) = Workbooks.Open(Filename:=FilesToOpen(i), UpdateLinks:=False, ReadOnly:=True)
            ' We don't update links as we don't want to change the file we're opening
            ' and we mark open it as 'Read Only' for the same reason. This is safer.
        c = c + 1 ' move the counter variable on one so we don't overwrite the workbook we've just opened
    Next i
    
    ' return the array of files we've opened to the user
    openFiles = Wb
End Function
' provided an array of open workbooks will get the 'change request' data from each of them
' and add them to the end of the 'SummarySheet' table
Private Sub processFiles(Wb() As Workbook)
    Dim i As Long
    Dim ws As Worksheet
    Dim SourceRange As range, TargetRange As range, FNR As range
    Dim MNFPath As String
    Dim myNewFolderName As String
    
    ' in order to be able to paste our data to the correct place we need to find the target point
    Set ws = ThisWorkbook.Worksheets("SummarySheet")
        ' note the use of 'ThisWorkbook', no matter which book is active this will always refer to the book that contains the code currently running
    Set TargetRange = ws.Cells(ws.Cells.Rows.Count, 2)
        ' by using the row count we avoid any problems if we're in compatibility mode or not, i.e. 65536 rows vs. 1048576
    Set TargetRange = TargetRange.End(xlUp)
        ' Target Range now points to the last filled row of the summary sheet (or the header)
        ' need to move it down one cell
    Set TargetRange = TargetRange.Cells(2, 1)   ' note that cell references are relative to the start point (base-1)
        'Set Filsave name value
 
      
    
    ' we now need to look at each change request file and pick up the data contained in the background sheet
    ' loop through each sheet
    For i = LBound(Wb) To UBound(Wb)
        With Wb(i)  ' saying 'With' stops us from having to type Wb(i) every time we need to refer to the workbook we're currently looking at
                    ' any time we want to refer to the workbook now we just start with the dot operator '.' instead
            
            ' we can only do the copy we want if we know the sheet we're looking for exists
            ' if there's only 1 sheet in the source book, it's probably not the right file so skip it
            If .Worksheets.Count >= 2 Then
                ' ideally we should do more testing of the source file before we try and copy from it, validate it is the file type intended
                
                Set ws = .Worksheets(2)   ' new use for Ws variable to refer to second worksheet (that's hidden)
                ' note you can look at the data in the hidden sheet without needing to make it visible
                
                ' find the data we want and get a range reference to it
                Set SourceRange = ws.Cells(2, 2) ' it's better to use index values to locate a cell, instead of the "A1" textual reference
                    ' it's used SheetRef.Cells(Row Number, Column Number) where the numbers start at 1, 1 for the top left corner of the sheet
                Set SourceRange = ws.range(SourceRange, SourceRange.End(xlToRight))
                    ' rather than use a fixed size area for the data, we define it by doing the VBA equivalent of Ctrl+Shift+Right Arrow
                    ' to discover the end point of the range we want (i.e. End(xlToRight)
                    ' the Range property takes the two arguments for the top left corner and bottom right corner of the are we want a reference to
                    
                ' now we can copy and paste the data across
                SourceRange.Copy
                TargetRange.PasteSpecial xlPasteValues
                Application.CutCopyMode = False
                    ' this turns off the copy area (marching ants border) so it doesn't prompt the user when we close the file
                
                ' make sure we move the target paste area on one ready for the next paste (if any)
                Set TargetRange = TargetRange.Cells(2, 1)
                
                 'FNR = TargetRange.Cells(1, -1).Value
                 MNFPath = "[URL="file://\\mnas01\accdata2\1"]\\mnas01\accdata2\1[/URL]. Finance Shared Services\FINANCE DATA & MI CHANGE\Change Request Log\"
                 myNewFolderName = MNFPath & "FNR"
                    CreateObject("Scripting.FileSystemObject").CreateFolder myNewFolderName
                                'ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myNewFolderName & "\Request Form", Quality:=xlQualityStandard,
                    'IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
                    
                Else
                MsgBox "Filename: '" & .Name & "', is missing the sheet we need. Skipping it."
                
        
                
            End If
            ' close the file we've finished with it now
            .Close SaveChanges:=False    ' false to not attempt to save changes (and not prompt the user for it)
        End With
    Next i
    
    ' by this point all the files that were opened should be closed and we should be looking at the completed SummarySheet table
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,523
Messages
6,125,318
Members
449,218
Latest member
Excel Master

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top