#REF! in formula after merging a workbook in Excel - excel

I'm merging Excel workbooks into one "summary.xls" using a VBA macro. The macro is executed from another open workbook. This original workbook has some formulas containing links to "summary" (like ='C:\[Summary.xls]Cell'!E3). For the process of merging, the original workbook "summary.xls" is deleted and rewritten. After rewriting all the formulas with the original links to summary have #ref! written in it and are broken and can not be automatically updated (='C:\[Summary.xls]#REF'!E4). The following passage is the one causing the mistake:
Workbooks(Filename).Close (False) 'add False to close without saving
' Kill srcFile 'deletes the file
Filename = Dir()
Does somebody has a suggestion how to solve the problem?
Whole code is based on that suggestion:
Option Explicit
Function IsSheetEmpty(sht As Worksheet) As Boolean
IsSheetEmpty = Application.WorksheetFunction.CountA(sht.Cells) = 0
End Function
Sub GetSheets()
Dim Path, Filename As String
Dim Sheet As Worksheet
Dim newBook As Workbook
Dim appSheets As Integer
Dim srcFile As String
Dim dstFile As String
Application.ScreenUpdating = False 'go faster by not waiting for display
'--- create a new workbook with only one worksheet
dstFile = ActiveWorkbook.Path & "AllSheetsHere.xlsx"
If Dir(dstFile) <> "" Then
Kill dstFile 'delete the file if it already exists
End If
appSheets = Application.SheetsInNewWorkbook 'saves the default number of new sheets
Application.SheetsInNewWorkbook = 1 'force only one new sheet
Set newBook = Application.Workbooks.Add
newBook.SaveAs dstFile
Application.SheetsInNewWorkbook = appSheets 'restores the default number of new sheets
Path = "C:\Temp\"
Filename = Dir(Path & "*.xls?") 'add the ? to pick up *.xlsx and *.xlsm files
Do While Filename <> ""
srcFile = Path & Filename
Workbooks.Open Filename:=srcFile, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
'--- potentially check for blank sheets, or only sheets
' with specific data on them
If Not IsSheetEmpty(Sheet) Then
Sheet.Copy After:=newBook.Sheets(1)
End If
Next Sheet
Workbooks(Filename).Close (False) 'add False to close without saving
Kill srcFile 'deletes the file
Filename = Dir()
Loop
'--- delete the original empty worksheet and save the book
newBook.Sheets(1).Delete
newBook.Save
newBook.Close
Application.ScreenUpdating = True 're-enable screen updates
End Sub

Internal sheet-to-sheet references within a workbook (Book1.xlsx) generally look like this:
=ABC!B23
But if you copy the worksheet with that reference to a new workbook, Excel will change it to an external reference back to the original workbook:
='[Book1.xlsx]ABC'!B23
There are several restrictions you'll have to place on references in your worksheets that you're copying into the single new workbook:
All sheet names in the destination workbook MUST be unique
Sheets named "ABC" in Book1 and "ABC" in Book2 would cause reference collisions in the destination workbook
One of the sheets must be renamed into a unique string
Sheet-to-sheet references that are completely internal to a workbook can be converted into similar references in the destination. References to external worksheets (in a different workbook) may be problematic and could require lots of additional logic to handle.
One option is to perform a wildcard search and replace on a worksheet after the Sheet.Copy is performed. The requirement here is that any sheet that is referenced must already be local to the new sheet in the destination book. (Otherwise, the "fixed-up" reference will still give you a #REF error.)
Sub test()
Dim area As Range
Dim farea As Range
'--- determines the entire used area of the worksheet
Set area = Range("A1").Resize(Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(What:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column)
'--- replaces all external references to make them internal references
area.Replace What:="[*]", Replacement:=""
End Sub
The other option is much cleaner and a neat trick. When you're copying worksheets into a new workbook, if you copy ALL the sheets in a single action then Excel preserves the sheet-to-sheet references as internal (and doesn't replace each reference with a filename prefix) because it knows that the sheet references will be there in the new workbook. Here's that solution in your code:
Option Explicit
Function IsSheetEmpty(sht As Worksheet) As Boolean
IsSheetEmpty = Application.WorksheetFunction.CountA(sht.Cells) = 0
End Function
Sub GetSheets()
Dim i As Integer
Dim Path, Filename As String
Dim sh As Worksheet
Dim newBook As Workbook
Dim appSheets As Integer
Dim srcFile As String
Dim dstFile As String
Dim dstPath As String
Dim wasntAlreadyOpen As Boolean
Dim name As Variant
Dim allSheetNames As Dictionary 'check VBA Editor->Tools->References->Microsoft Scripting Runtime
Dim newSheetNames As Dictionary
Dim newNames() As String
Application.ScreenUpdating = False 'go faster by not waiting for display
'--- create a new workbook with only one worksheet
dstFile = "AllSheetsHere.xlsx"
dstPath = ActiveWorkbook.Path & "\" & dstFile
wasntAlreadyOpen = True
If Dir(dstPath) = "" Then
'--- the destination workbook does not (yet) exist, so create it
appSheets = Application.SheetsInNewWorkbook 'saves the default number of new sheets
Application.SheetsInNewWorkbook = 1 'force only one new sheet
Set newBook = Application.Workbooks.Add
newBook.SaveAs dstPath
Application.SheetsInNewWorkbook = appSheets 'restores the default number of new sheets
Else
'--- the destination workbook exists, so ...
On Error Resume Next
wasntAlreadyOpen = False
Set newBook = Workbooks(dstFile) 'connect if already open
If newBook Is Nothing Then
Set newBook = Workbooks.Open(dstPath) 'open if needed
wasntAlreadyOpen = True
End If
On Error GoTo 0
'--- make sure to delete any/all worksheets so we're only left
' with a single empty sheet named "Sheet1"
Application.DisplayAlerts = False 'we dont need to see the warning message
Do While newBook.Sheets.Count > 1
newBook.Sheets(newBook.Sheets.Count).Delete
Loop
newBook.Sheets(1).name = "Sheet1"
newBook.Sheets(1).Cells.ClearContents
newBook.Sheets(1).Cells.ClearFormats
Application.DisplayAlerts = True 'turn alerts back on
End If
'--- create the collections of sheet names...
' we need to make sure that all of the sheets added to the newBook have unique
' names so that any formula references between sheets will work properly
' LIMITATION: this assumes sheet-to-sheet references only exist internal to
' a single workbook. External references to sheets outside of the
' source workbook are unsupported in this fix-up
Set allSheetNames = New Dictionary
allSheetNames.Add "Sheet1", 1
Path = "C:\Temp\"
Filename = Dir(Path & "*.xls?") 'add the ? to pick up *.xlsx and *.xlsm files
Do While Filename <> ""
srcFile = Path & Filename
Workbooks.Open Filename:=srcFile, ReadOnly:=True
'--- first make sure all the sheet names are unique in the destination book
Set newSheetNames = New Dictionary
For Each sh In ActiveWorkbook.Sheets
If Not IsSheetEmpty(sh) Then
'--- loop until we get a unique name
i = 0
Do While allSheetNames.Exists(sh.name)
sh.name = sh.name & "_" & i 'rename until unique
i = i + 1
Loop
allSheetNames.Add sh.name, i
newSheetNames.Add sh.name, i
End If
Next sh
'--- we're going to copy ALL of the non-empty sheets to the new workbook with
' a single statement. the advantage of this method is that all sheet-to-sheet
' references are preserved between the sheets in the new workbook WITHOUT
' those references changed into external references
ReDim newNames(0 To newSheetNames.Count - 1)
i = 0
For Each name In newSheetNames.Keys
newNames(i) = name
i = i + 1
Next name
ActiveWorkbook.Sheets(newNames).Copy After:=newBook.Sheets(1)
Workbooks(Filename).Close (False) 'add False to close without saving
Kill srcFile 'deletes the file
'--- get the next file that matches
Filename = Dir()
Loop
'--- delete the original empty worksheet and save the book
If newBook.Sheets.Count > 1 Then
newBook.Sheets(1).Delete
End If
newBook.Save
'--- leave it open if it was already open when we started
If wasntAlreadyOpen Then
newBook.Close
End If
Application.ScreenUpdating = True 're-enable screen updates
End Sub

If you still have reference in your workbook to the cells being referenced (and from your example, you do), and if all of your #REF! errors used to point to a single sheet, there is an easy fix.
CTRL+H brings up the REPLACE function.
Simply enter #REF! in the "find" box, and Sheet1 in the "replace" box, and all references will now point to sheet1 in the same summary.xls workbook.

I've added a further workbook containig the referencins formulas. This one is closed during the whole procedure of deleting and summarizing the worksheets. The new workbook opens after this, therefore the referencing mistake is avoided.

Related

VBA code no problem while debugging, but 90% of the time silently closes excel when ran

Wrote some code below to help me save some time saving files, the below is the shorter version which only saves one worksheet.
Sometimes it works perfectly, but most of the time it just silently crashes Excel with no error warning.
Nothing wrong while debugging... Not sure if ThisWorkbook.Sheets might be causing the issue?
Sub Save_CPC()
'Define the sheets to copy
Dim sheetsToCopy As Variant
sheetsToCopy = Array("RWF CPC")
'Create a new workbook
Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add
'Loop through the sheets to copy
For i = 0 To UBound(sheetsToCopy)
'Copy the sheet to the new workbook
ThisWorkbook.Sheets(sheetsToCopy(i)).Copy Before:=newWorkbook.Sheets(1)
Next i
'Break links in the new workbook
newWorkbook.BreakLink Name:=ThisWorkbook.Name, Type:=xlExcelLinks
'Hide the sheet Sheet1 in new workbook
newWorkbook.Sheets("Sheet1").Visible = False
'Save the new workbook in the original folder
Dim saveName As String
saveName = ThisWorkbook.Sheets("Macros").Range("B13").Value
newWorkbook.SaveAs ThisWorkbook.Path & "\" & saveName & ".xlsx"
End Sub
Thanks in advance!!
Should copy and save worksheet as new spreadsheet with given name in current folder.
Copy Worksheets To a New Workbook
In One Go
Note that you can copy all the worksheets in one go as suggested by BigBen in the comments:
ThisWorkbook.Sheets(sheetsToCopy).Copy
Dim NewWorkbook As Workbook: Set NewWorkbook = Workbooks(Workbooks.Count)
The major drawback is that the worksheets in the new workbook will appear in the order they are appearing in the old workbook which may not necessarily be the order they are appearing in the array.
Additionally, at least one of the worksheets needs to be visible, and very hidden worksheets will not be copied.
Loop
Option Explicit
Sub SaveCPC()
' Start error-handling routine.
On Error GoTo ClearError
' Populate an array with the names of the worksheets to copy.
Dim sheetsToCopy() As Variant: sheetsToCopy = VBA.Array("RWF CPC")
' 'VBA.' ensures a zero-based array no matter what ('Option Base'-related).
' If you don't do this, instead of both occurrences of '0',
' use the recommended (more accurate) 'LBound(sheetsToCopy)'.
' Declare new variables to be used in the loop.
Dim NewWorkbook As Workbook, OldWorksheet As Worksheet, i As Long
' Loop through the worksheet names in the array.
For i = 0 To UBound(sheetsToCopy)
' Reference the worksheet to be copied.
Set OldWorksheet = ThisWorkbook.Sheets(sheetsToCopy(i))
If i = 0 Then ' on the first iteration...
' Add a new workbook containing only the first copied worksheet.
OldWorksheet.Copy
' Reference this new workbook.
Set NewWorkbook = Workbooks(Workbooks.Count)
Else ' on any but the first iteration
' Copy the worksheet as the last sheet in the new workbook.
OldWorksheet.Copy After:=NewWorkbook.Sheets(NewWorkbook.Sheets.Count)
End If
Next i
' Break links in the new workbook.
NewWorkbook.BreakLink Name:=ThisWorkbook.Name, Type:=xlExcelLinks
' Retrieve the base name of the new workbook.
Dim saveName As String
saveName = ThisWorkbook.Sheets("Macros").Range("B13").Value
' Save the new workbook in the original folder.
Application.DisplayAlerts = False ' overwrite without confirmation.
NewWorkbook.SaveAs ThisWorkbook.Path & "\" & saveName
Application.DisplayAlerts = True
' Inform.
MsgBox "CPC saved.", vbInformation
ProcExit:
Exit Sub
ClearError:
' Continue error-handling routine.
MsgBox "Run-time error '" & Err.Number & "':" & vbLf & vbLf & Err.Description
Resume ProcExit
End Sub

What is the code to skip or replace the existing data in the sheet being added?

Here is my code of adding a sheet in multiple workbooks. I want to know how to skip or replace the exiting data in those multiple workbooks.
Sub AddingChklist()
ActiveWorkbook.Save
Dim path As String
Dim file As String
Dim Chklist As Workbook
path = "C:\Users\Documents\Macro Project\"
file = Dir(path)
Application.ScreenUpdating = False
Do While Not file = ""
Workbooks.Open (path & file)
Set Chklist = ActiveWorkbook
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Recon Checklist"
ThisWorkbook.Sheets("Recon Checklist").Range("A1:C25").Copy Destination:=Chklist.Sheets("Recon Checklist").Range("A1")
Range("A1:C25").EntireColumn.AutoFit
Range("A1:C25").EntireRow.AutoFit
Chklist.Save
Chklist.Close
file = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Checklist has been added to all the files"
End Sub
Copied from discussion below:-
My question was if the recon checklist sheet was already in one of the workbooks while running this macro. How we need to skip or replace the existing sheet.
Please try this code. In order to do away with the heavy flicker connected with opening many files in succession this procedure creates an invisible instance of Excel dedicated to this task. While this works very smoothly, it unfortunately raises the problem of not being able to copy formatting from one instance of Excel to another. Therefore my code only copies values. However, you have full access to each new sheet. For now only AutoFit is applied but you could do a lot of more formatting at that point if you feel the need.
Sub AddingChklist()
' 242
Const WsName As String = "Recon Checklist" ' Ws actual name
Dim Xl As New Excel.Application ' dedicated instance of Excel
Dim ChkList As Variant ' Checklist
Dim Path As String
Dim File As String
Dim Sp() As String ' split of File
Dim Wb As Workbook ' loop object
Dim Ws As Worksheet ' loop object: CheckList
Xl.Visible = True ' hide the newly opened workbooks
Path = "C:\Users\Documents\Macro Project\"
ChkList = ThisWorkbook.Sheets(WsName).Range("A1:C25").Value
File = Dir(Path)
Do While Not File = ""
Sp = Split(File, ".") ' process only Excel workbooks
If InStr(1, Sp(UBound(Sp)), "xls", vbTextCompare) = 1 Then
Set Wb = Xl.Workbooks.Open(Path & File)
Application.StatusBar = "Processing " & Wb.Name
On Error Resume Next
Set Ws = Wb.Worksheets(WsName)
If Err.Number = 9 Then
On Error GoTo 0
Set Ws = Wb.Sheets.Add(Before:=Wb.Sheets(1))
Ws.Name = WsName
End If
With Ws
.Cells.ClearContents
.Cells(1, 1).Resize(UBound(ChkList), UBound(ChkList, 2)).Value = ChkList
.Columns.AutoFit
.Rows.AutoFit
End With
Wb.Close SaveChanges:=True
End If
File = Dir
Loop
Xl.Quit ' close the dedicated instance of Excel
' MsgBox "Checklist has been added to all the files"
Application.StatusBar = "Checklist has been added to all the files"
End Sub
Observe that the code first looks for an existing tab by the same name. If such a sheet doesn't exist it will be created. Any existing sheet will be wiped clean. Finally, the contents of your template will be pasted to the new/clean sheet.
Note that I added a test to the code to ensure that only Excel workbooks will be processed.

How to extract data from multiple closed excel workbooks for placing in a separate workbook in different worksheets through VBA?

(Beginner VBA coder here!)
Does anyone know how to extract multiple, specific cell data from multiple closed workbooks that have the same worksheet format?
I am currently tasked to copy very specific data from certain cells from many different and new (but same format) sources and transfer them into another group of specific cells in an existing masterlist with different worksheets.
This is the code I wished would help, but it is lacking in too many ways as compared to what I need...
Sub Importsheet()
Dim Importsheet As Worksheet
'import worksheet from a closed workbook
Sheets.Add Type:= _
'e.g. directory below
"C:\Users\Loli\Desktop\Testing1.xlsx"
End Sub
This code helps me get the sheets out of the closed source workbook but not the specifically placed cells in the closed source excel. It also can't paste the data in specifically placed cells in different sheets in the destination excel.
It is very difficult to completely understand your requirements as it seems like sometimes you want to copy a range and some other times a single cell, so to point you in the right direction my answer only shows how to open and copy the relevant Sheet into your master workbook to then be able to reference the cell/ranges you want
(I would once you get your data then delete the Worksheet, so that your master doesn't suddenly becomes massive in size):
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook
Dim vfilename As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook") 'open dialog to choose the file you want, you can change this to loop through a folder if they are all in there.
If sImportFile = "False" Then 'check if a file was selected before importing
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile 'open the selected file
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("Raw_Data") Then ' you should change this to the date, you can do this easily by using a variable such as if SheetExists(variableDate) then, where variableDate = "12/12/2017" or something similar
Set wsSht = .Sheets("Raw_Data")
wsSht.Copy before:=sThisBk.Sheets("Sheet1") 'copy the worksheet into your master
'WsSht.range("A1:B2").copy Destination:=sThisBk.Sheets("Temp").Range("A1").paste xlpastevalues 'use this to copy a specified range in this case A1:B2 to a sheet in master workbook called Temp A1
Else
MsgBox "There is no sheet with name :Raw_Data in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function

Merging workbooks into a new file

I'm trying to merge multiple Excel files from one Folder into a new file. I've found a solution on the Internet, that is adding my files into an open one. I'm not really into VBA Excel, so I think it's a basic problem, but I can't do it, things I've tried haven't worked properly. I would like to change the following code to create a new file called "summary" in the "Path" and copy the Sheets into this new file, overwriting the file every time I do it and deleting the several source files after doing this.
Is there a possibility of merging all those files into one without opening everyone of it?
Sub GetSheets()
Path = "C:\Merging\"
FileName = Dir(Path & "*.xls")
Do While FileName <> ""
Workbooks.Open FileName:=Path & FileName, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(FileName).Close
FileName = Dir()
Loop
End Sub
Your code almost works as is, just needs a couple of slight tweaks. I also agree with #AnalystCave that if this is a repeating exercise, you may consider a more streamlined solution. But this will work for you.
EDIT: changed to deal with existing destination file -- if it exists and is open, then connect to it otherwise open it; then delete all sheets in the existing file to prepare for the copies
Option Explicit
Function IsSheetEmpty(sht As Worksheet) As Boolean
IsSheetEmpty = Application.WorksheetFunction.CountA(sht.Cells) = 0
End Function
Sub GetSheets()
Dim Path, Filename As String
Dim Sheet As Worksheet
Dim newBook As Workbook
Dim appSheets As Integer
Dim srcFile As String
Dim dstFile As String
Dim dstPath As String
Dim wasntAlreadyOpen As Boolean
Application.ScreenUpdating = False 'go faster by not waiting for display
'--- create a new workbook with only one worksheet
dstFile = "AllSheetsHere.xlsx"
dstPath = ActiveWorkbook.Path & "\" & dstFile
wasntAlreadyOpen = True
If Dir(dstPath) = "" Then
'--- the destination workbook does not (yet) exist, so create it
appSheets = Application.SheetsInNewWorkbook 'saves the default number of new sheets
Application.SheetsInNewWorkbook = 1 'force only one new sheet
Set newBook = Application.Workbooks.Add
newBook.SaveAs dstFile
Application.SheetsInNewWorkbook = appSheets 'restores the default number of new sheets
Else
'--- the destination workbook exists, so ...
On Error Resume Next
wasntAlreadyOpen = False
Set newBook = Workbooks(dstFile) 'connect if already open
If newBook Is Nothing Then
Set newBook = Workbooks.Open(dstPath) 'open if needed
wasntAlreadyOpen = True
End If
On Error GoTo 0
'--- make sure to delete any/all worksheets so we're only left
' with a single empty sheet named "Sheet1"
Application.DisplayAlerts = False 'we dont need to see the warning message
Do While newBook.Sheets.Count > 1
newBook.Sheets(newBook.Sheets.Count).Delete
Loop
newBook.Sheets(1).Name = "Sheet1"
newBook.Sheets(1).Cells.ClearContents
newBook.Sheets(1).Cells.ClearFormats
Application.DisplayAlerts = True 'turn alerts back on
End If
Path = "C:\Temp\"
Filename = Dir(Path & "*.xls?") 'add the ? to pick up *.xlsx and *.xlsm files
Do While Filename <> ""
srcFile = Path & Filename
Workbooks.Open Filename:=srcFile, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
'--- potentially check for blank sheets, or only sheets
' with specific data on them
If Not IsSheetEmpty(Sheet) Then
Sheet.Copy After:=newBook.Sheets(1)
End If
Next Sheet
Workbooks(Filename).Close (False) 'add False to close without saving
Kill srcFile 'deletes the file
Filename = Dir()
Loop
'--- delete the original empty worksheet and save the book
If newBook.Sheets.Count > 1 Then
newBook.Sheets(1).Delete
End If
newBook.Save
'--- leave it open if it was already open when we started
If wasntAlreadyOpen Then
newBook.Close
End If
Application.ScreenUpdating = True 're-enable screen updates
End Sub
Firstly, regardless of your solution you will still need to OPEN every Excel workbook if you want to merge all of them.
Secondly, I think you might want to rephrase your question to "Is there a possibility of merging all those files into one faster or in any easier way?"
From the level of Excel VBA there is really no other way then opening each Workbook within the same Application level. If this is a one-time exercise I would stick to the code you already have and bear with it.
However, if this is an exercise you will be doing repeatedly and need an efficient solution, your only option is resorting to the OpenXML format which does not require a heavyweight Excel process e.g. creating a C# solution using the ClosedXML library. This will definitely reduce the time needed to consolidate your workbooks.

Copy one worksheet to multiple identical workbooks using VBA

I have a workbook containing one worksheet ("DB Output" or Sheet 34) which I would like to copy to several (around 45) files in within the same folder.
None of the target files have an existing sheet named "DB Output" - the objective is to find a way to insert a copy of this sheet, forumlas and all, into each one.
The range of cells on that sheet that needs to be copied to a sheet of the same name in each book is A1:PE5
The sheet contains references to cells in the book it is currently in, however as the files which I am seeking to copy the worksheet to all share the same template, I want the references to be to the local file, not the original one.
I've tried looking at RDBMerge, however it seems that is for merging sheets, and while I do want to do that, it will not help me do it multiple times quickly.
Likewise I have looked on SO for similar situations, this is the closest, however my attempts to adapt that code have failed as I only have a single workskeet. Never the less, as it is always useful to inlcude what you have already tried, here is my existing attempt:
Option Explicit
Public Sub splitsheets()
Dim srcwb As Workbook, trgwb As Workbook
Dim ws As Worksheet, t1ws As Worksheet
Dim rng1 As Range
Dim trgnm As String
Dim fpath As String
Application.ScreenUpdating = False
'--> Set this to the location of the target workbooks
fpath = "C:/file/path/"
Set srcwb = ThisWorkbook
For Each ws In srcwb.Worksheets
trgnm = ws.Name
'--> Change A1:B3 to the range to be copied to inside page
Set rng1 = srcwb.Sheets(trgnm).Range("A1:PE5")
Set trgwb = Workbooks.Open(fpath & trgnm & ".xlsm")
With trgwb
Set t1ws = .Sheets("DB Output")
End With
'--> Change A1:B3 to the range where you want to paste
rng1.Copy t1ws.Range("A1:PE5")
trgwb.Close True
Next
Application.ScreenUpdating = True
End Sub
However this starts with the first sheet in the workbook that contains DB Output (the sheet to be copied) and gives an error that "NameOfSheet1.xlsm" does not exist in that directory (which it does not).
Any help is much appreciated.
This should copy from the active workbook to all files in a directory. If you need help modifying it to fit your specific use let me know!
Edit: fixed code to only copy A1:PE5 and save each workbook.
Sub Example()
Dim path As String
Dim file As String
Dim wkbk As Workbook
path = "C:\Test\"
file = Dir(path)
Application.DisplayAlerts = False
Do While Not file = ""
Workbooks.Open (path & file)
Set wkbk = ActiveWorkbook
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "DB Output"
ThisWorkbook.Sheets("DB Output").Range("A1:PE5").Copy Destination:=wkbk.Sheets("DB Output").Range("A1")
wkbk.Save
wkbk.Close
file = Dir
Loop
Application.DisplayAlerts = True
End Sub
Please note that I did not add error handling so this could break if the active workbook is included in the directory you are trying to copy or if a sheet with the same name already exists in the workbook. If this is an issue let me know and I will add error handling.

Resources