Copying duplicating issue - excel

i wrote the next code to copy a certain worksheet from my active workbook to multiple woorkbooks but it keeps duplicating the copies,thats my first problem,
the next one i want that code to effect the folder and subfolders inside it how to do it.
the code is:
Option Explicit
Public Sub CopySheetToAllWorkbooksInFolder()
Dim sourceWorkbook As Workbook
Dim sourceSheet As Worksheet
Dim destinationWorkbook As Workbook
Dim folder As String, filename As String
'Worksheet in active workbook to be copied as a new sheet to the destination workbook
Set sourceWorkbook = ActiveWorkbook
Set sourceSheet = sourceWorkbook.Worksheets("pay")
'Folder containing the destination workbooks
folder = "J:\2021\hager\test\"
filename = Dir(folder & "*.xlsx", vbNormal)
While Len(filename) <> 0
Debug.Print folder & filename
Set destinationWorkbook = Workbooks.Open(folder & filename)
sourceSheet.Copy after:=destinationWorkbook.Sheets(1)
destinationWorkbook.ChangeLink Name:=sourceWorkbook.Name, NewName:=destinationWorkbook.Name
destinationWorkbook.Close True
filename = Dir() ' Get next matching file
Wend
End Sub
as pay is the worksheet and the folder is my targeted folder .

Add Worksheet to Multiple Files
This will copy an active workbook's worksheet to all relevant (.xlsx) files in a folder and all of its subfolders (/s).
It will skip the files already containing the worksheet.
If the code is in the workbook containing the worksheet (Pay), replace ActiveWorkbook with ThisWorkbook.
Option Explicit
Sub CopySheetToAllWorkbooksInFolder()
Const ProcName As String = "CopySheetToAllWorkbooksInFolder"
On Error GoTo ClearError
Const dFolderPath As String = "J:\2021\hager\test\"
Const dFilePattern As String = "*.xlsx"
Const swsName As String = "Pay"
Dim fCount As Long
Dim dFilePaths() As String
dFilePaths = ArrFilePaths(dFolderPath, dFilePattern)
If UBound(dFilePaths) = -1 Then Exit Sub ' no files found
Dim swb As Workbook: Set swb = ActiveWorkbook ' ThisWorkbook '
Dim sws As Worksheet: Set sws = swb.Worksheets(swsName)
Dim dwb As Workbook
Dim n As Long
For n = 0 To UBound(dFilePaths)
Debug.Print "Opening... " & dFilePaths(n)
Set dwb = Workbooks.Open(dFilePaths(n))
If Not SheetExists(dwb, swsName) Then
sws.Copy After:=dwb.Sheets(1)
'dwb.ChangeLink swb.Name, dwb.Name ' doesn't work for me
fCount = fCount + 1
Debug.Print "Worksheet added to... " & fCount & ". " & dFilePaths(n)
End If
dwb.Close SaveChanges:=True
Next n
MsgBox "Worksheet inserted in " & fCount & " workbook(s).", vbInformation
ProcExit:
Exit Sub
ClearError:
Debug.Print "'" & ProcName & "' Rte '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns the file paths of the files of a folder in an array.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ArrFilePaths( _
ByVal FolderPath As String, _
Optional ByVal FilePattern As String = "*.*", _
Optional ByVal DirSwitches As String = "/s/b/a-d") _
As Variant
Const ProcName As String = "ArrFilePaths"
On Error GoTo ClearError
Dim pSep As String: pSep = Application.PathSeparator
If Right(FolderPath, 1) <> pSep Then FolderPath = FolderPath & pSep
Dim ExecString As String ' '%comspec%' or 'cmd.exe' ?
ExecString = "%comspec% /c Dir """ _
& FolderPath & FilePattern & """ " & DirSwitches
Dim Arr() As String: Arr = Split(CreateObject("WScript.Shell") _
.Exec(ExecString).StdOut.ReadAll, vbCrLf)
If UBound(arr) > 0 Then
ReDim Preserve arr(0 To UBound(arr) - 1)
End If
ArrFilePaths = arr
ProcExit:
Exit Function
ClearError:
Debug.Print "'" & ProcName & "' Rte '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns a boolean indicating wether a sheet, defined
' by its name ('SheetName'), exists in a workbook ('wb').
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function SheetExists( _
ByVal wb As Workbook, _
ByVal SheetName As String) _
As Boolean
On Error GoTo ClearError
Dim Sh As Object: Set Sh = wb.Sheets(SheetName)
SheetExists = True
ProcExit:
Exit Function
ClearError:
Resume ProcExit
End Function

This loops through workbooks in the folder and subfolders. It only copies the pay sheet if it doesn't exist.
Option Explicit
Public Sub CopySheetToAllWorkbooksInFolder()
Const WS_NAME = "pay"
Const folder = "J:\2021\hager\test\" ' destination workbooks
Dim wbSrc As Workbook, wbDest As Workbook
Dim wsSrc As Worksheet, wsDest As Worksheet
Dim FSO As Object, ts As Object
Dim flds As Collection, fld As Object, f As Object
Dim i As Long, n As Long, bExists As Boolean, logfile As String
' logfile
logfile = Format(Now, "yyyyddmm_HHMMSS") & "_log.txt"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set ts = FSO.createTextFile(logfile)
Set wbSrc = ActiveWorkbook
Set wsSrc = wbSrc.Sheets(WS_NAME)
Set flds = New Collection
If FSO.FolderExists(folder) Then
' collection of folders and subfolders
Call GetFolders(FSO, folder, flds)
'scan folders
Application.ScreenUpdating = False
For i = 1 To flds.Count
ts.writeLine "---- Folder = " & flds(i)
' scan folder for files
For Each f In flds(i).Files
If f.Name Like "*.xlsx" Then
Set wbDest = Workbooks.Open(f.Path)
' check if sheet already exists
bExists = False
For Each wsDest In wbDest.Sheets
If wsDest.Name = WS_NAME Then
bExists = True
Exit For
End If
Next
' copy sheet if not exists
If bExists = False Then
wsSrc.Copy after:=wbDest.Sheets(1)
wbDest.ChangeLink Name:=wbSrc.Name, NewName:=wbDest.Name
wbDest.Close savechanges:=True
n = n + 1
ts.writeLine f.Path & " inserted " & WS_NAME
Else
wbDest.Close savechanges:=False
ts.writeLine f.Path & " existing sheet " & WS_NAME
End If
Else
ts.writeLine f.Path & " Skipped"
End If
Next
Next
MsgBox n & " sheets inserted see " & logfile, vbInformation
Else
MsgBox "Folder : " & folder, vbCritical, "Folder not found"
End If
ts.Close
Application.ScreenUpdating = True
End Sub
Sub GetFolders(FSO, s As String, ByRef flds)
Dim fld As Object
Set fld = FSO.getfolder(s)
flds.Add fld
For Each fld In fld.subfolders
Call GetFolders(FSO, fld.Path, flds) ' recurse
Next
End Sub

Please, use the next function, which will return an array of all files matching the ".xls*" extension criteria:
Private Function allFiles(strFold As String, Optional ext As String = "") As Variant 'super, super fast...
Dim arr
arr = Filter(Split(CreateObject("wscript.shell").exec("cmd /c dir """ & strFold & """ /b /s").StdOut.ReadAll, vbCrLf), "\")
If ext <> "" Then
Dim arrFin, arrExt, El, i As Long
ReDim arrFin(UBound(arr))
For Each El In arr
arrExt = Split(El, ".")
If arrExt(UBound(arrExt)) Like ext Then
arrFin(i) = El: i = i + 1
End If
Next El
ReDim Preserve arrFin(i - 1)
allFiles = arrFin
Else
allFiles = arr
End If
End Function
Then use it in your code in the next way:
Public Sub CopySheetToAllWorkbooksInFolder()
Dim sourceWorkbook As Workbook, sourceSheet As Worksheet, destinationWorkbook As Workbook
Dim folder As String, arr, El
'Worksheet in active workbook to be copied as a new sheet to the destination workbook
Set sourceWorkbook = ActiveWorkbook
Set sourceSheet = sourceWorkbook.Worksheets("pay")
'Folder containing the destination workbooks
folder = "J:\2021\hager\test\"
arr = allFiles(folder, "xls*")
For Each El In arr
Debug.Print El: Stop 'run the code line by line pressing F8
Set destinationWorkbook = Workbooks.Open(El)
sourceSheet.copy After:=destinationWorkbook.Sheets(1)
destinationWorkbook.ChangeLink Name:=sourceWorkbook.Name, newName:=destinationWorkbook.Name
destinationWorkbook.Close True
Next El
End Sub
When the above code will stop on the line Debug.Print El, run it line by line, pressing F8 and see what happends. If ie work as you need, please comment the code line in discussion and press F5 to run all of it.
Please, send some feedback after testing it.

Related

VBA to import tables of variable lengths from several excel files into a main workbook?

I receive periodical data from several excel files, always in the same format, and I need to import it to a main workbook (sheet called “Results”).
Previously, the several excel files only had 7 cells in the sheet to be imported and the code I had did the job. However, now the several excel files contain a table (A12:D) with a variable last row, and the table’s data needs to be imported. I tried to tweak the code and put autofilters there for importing, but nothing has worked.
The code below does:
Opens each file saved in specific location
Imports 7 specific cells with data into main spreadsheet – that’s the part that no longer applies
Closes the file and moves it to another location
Loops until all files in original location are imported in the main spreadsheet and files get moved to the end location
Please help in how step 2 could be changed so it imports a variable length table from row 12 to the last row to the main workbook in spreadsheet “Results”?
Code:
Dim sFile As String
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long
Dim lastRow As Long
Dim PathStart As String
Dim PathEnd As String
'Prep
PathStart = ThisWorkbook.Sheets("MASTER").Range("B9") & "\"
PathEnd = ThisWorkbook.Sheets("MASTER").Range("B10") & "\"
lastRow = Sheets("Results").Cells.SpecialCells(xlCellTypeLastCell).Row + 1
If Not FileFolderExists(PathStart) Then
MsgBox "Received folder does not exist"
Exit Sub
End If
If Dir(PathStart & "*.*") = "" Then
MsgBox "There are no files to import"
End If
On Error GoTo errHandler
Application.ScreenUpdating = False
Set wsTarget = Sheets("Results")
'Step 1 – go the original folder
sFile = Dir(PathStart & "*.xls*")
Do Until sFile = ""
Set wbSource = Workbooks.Open(PathStart & sFile)
Set wsSource = wbSource.Worksheets("Form")
'Step 2 – import data
With wsTarget
.Range("A" & lastRow).Value = wsSource.Range("C6").Value
.Range("B" & lastRow).Value = wsSource.Range("C8").Value
.Range("C" & lastRow).Value = wsSource.Range("C10").Value
.Range("D" & lastRow).Value = wsSource.Range("B13").Value
.Range("E" & lastRow).Value = wsSource.Range("C13").Value
.Range("F" & lastRow).Value = wsSource.Range("D13").Value
.Range("G" & lastRow).Value = wsSource.Range("E13").Value
'source filename in the last column
.Range("H" & lastRow).Value = Mid(sFile, 1, InStr(1, sFile, ".") - 1)
End With
'Step 3-4 – move file and go to next
wbSource.Close savechanges:=False
Name PathStart & sFile As PathEnd & sFile
lastRow = lastRow + 1
sFile = Dir()
Loop
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
Thank you
One of attempts tried without luck were to put a filter for each of the files to be imported, and then only import the used rows into the main spreadsheet, but didn't succed:
wsSource.Range("A11").AutoFilter Field:=2, Criteria1:="<>"
wsSource.Range("A12" & ":" & "A" & Rows.Count).End(xlUp).Offset(1).Copy
wsTarget.Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValues
Option Explicit
Sub GetData()
Const FORM = "FORM" ' sheet with data on
Dim wbSource As Workbook, wsSource As Worksheet
Dim wsMaster As Worksheet, wsTarget As Worksheet, rngTarget As Range
Dim PathStart As String, PathEnd As String, sFile As String
Dim n As Long, i As Long, r As Long, lastrow As Long
' Prep
With ThisWorkbook
Set wsMaster = .Sheets("MASTER")
Set wsTarget = .Sheets("Results")
End With
With wsMaster
PathStart = .Range("B9") & "\"
PathEnd = .Range("B10") & "\"
End With
Dim fso As Object, oFolder As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(PathStart) Then
MsgBox "ERROR - folder PathStart does not exist", vbCritical, PathStart
Exit Sub
ElseIf Not fso.FolderExists(PathEnd) Then
MsgBox "ERROR - folder PathEnd does not exist", vbCritical, PathEnd
Exit Sub
End If
' go the original folder
sFile = Dir(PathStart & "*.xls*")
If sFile = "" Then
MsgBox "ERROR - no files to import", vbCritical, PathStart
Exit Sub
End If
With wsTarget
lastrow = .Cells.SpecialCells(xlCellTypeLastCell).Row + 1
Set rngTarget = .Cells(lastrow, "A")
MsgBox "Import starts at row " & rngTarget.Row, vbInformation
End With
' open each files
Application.ScreenUpdating = False
Do Until sFile = ""
Set wbSource = Workbooks.Open(PathStart & sFile)
On Error Resume Next
Set wsSource = wbSource.Sheets(FORM)
On Error GoTo 0
If wsSource Is Nothing Then
MsgBox "ERROR - no sheet Form in " & sFile, vbExclamation, PathStart
Else
With wsSource
' table at A12:D?
r = .Cells(.Rows.Count, "A").End(xlUp).Row
If r >= 12 Then
i = r - 11
rngTarget.Resize(i, 4).Value2 = .Range("A12:D" & r).Value2
'source filename in the column H
rngTarget.Offset(, 7).Value = fso.getBaseName(sFile)
' next file
Set rngTarget = rngTarget.Offset(i)
n = n + 1
End If
End With
End If
wbSource.Close savechanges:=False
Set wsSource = Nothing
'move file and go to next
Name PathStart & sFile As PathEnd & sFile
sFile = Dir()
Loop
Application.ScreenUpdating = True
MsgBox n & " tables imported", vbInformation
End Sub

Splitting Sheets with Same Name Range in One Excel Workbook - Excel VBA

I have some Excel workbooks which contains more than 100 sheets. The sheet names like below;
TTBMA2453_Speclist, TTBMA2454_Speclist, TTBMA2455_Speclist and goes on..
WBXXTTBMA2453_Featurelist, WBXXTTBMA2454_Featurelist, WBXXTTBMA2455_Featurelist and goes on..
WBXXTTBMA2453_Corelist, WBXXTTBMA2454_Corelist, WBXXTTBMA2455_Corelist and goes on..
I want to split all spec, feature and corelist sheets which are starting with same speclist name in the same workbook and merge/save to another Excel workbook in a specific file using Excel VBA.
(e.g combining TTBMA2453_Speclist, WBXXTTBMA2453_Featurelist WBXXTTBMA2453_Corelist and copy them as new workbook with original sheets)
Please find the code sample I have. This code splits sheets of the same name (which I added manually) into workbooks. However, this code does not re-merge the sheets in a different workbook and sheet names are entered manually. So, that's not what I want.
Sub SplitEachWorksheet()
Dim FPath As String
FPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim ws As Worksheet
Dim fnameList, fnameCurFile As Variant
Dim countFiles, countSheets As Integer
Dim wksCurSheet As Worksheet
Dim wbkCurBook, wbkSrcBook As Workbook
For Each ws In ThisWorkbook.Worksheets
If Left$(ws.Name, 9) = "TTBMA2453" Then ' <--- added an IF statement
ws.Copy
Application.ActiveWorkbook.SaveAs Filename:=FPath & "\" & ws.Name & ".xlsx"
Application.ActiveWorkbook.Close False
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Option Explicit
Sub SplitEachWorksheet()
Dim wb As Workbook, wbNew As Workbook, ws As Worksheet
Dim num As Collection, n, dict As Object
Dim FPath As String
FPath = Application.ActiveWorkbook.Path
Set num = new Collection
Set dict = CreateObject("Scripting.Dictionary")
Set wb = ThisWorkbook
For Each ws In wb.Worksheets
If ws.Name Like "*_Speclist" Then
num.Add Left(ws.Name, Len(ws.Name) - 9)
End If
dict.Add ws.Name, ws.Index
Next
' check sheets
Dim msg As String, s As String
For Each n In num
s = "WBXX" & n & "_Corelist"
If Not dict.exists(s) Then
msg = msg & vbLf & s & " missing"
End If
s = "WBXX" & n & "_Featurelist"
If Not dict.exists(s) Then
msg = msg & vbLf & s & " missing"
End If
Next
If Len(msg) > 0 Then
MsgBox msg, vbCritical
Exit Sub
End If
' check workbooks
Application.ScreenUpdating = False
For Each n In num
wb.Sheets(n & "_Speclist").Copy
Set wbNew = ActiveWorkbook
wb.Sheets("WBXX" & n & "_Featurelist").Copy after:=wbNew.Sheets(1)
wb.Sheets("WBXX" & n & "_Corelist").Copy after:=wbNew.Sheets(2)
wbNew.SaveAs Filename:=FPath & "\" & n
wbNew.Close False
Next
Application.ScreenUpdating = True
' result
MsgBox num.Count & " worksbooks created in " & FPath, vbInformation
End Sub

Remove duplicate rows in Excel from a particular sheet

Thanks in advance for helping!
I am currently using the below code to populate multiple .csv files into one sheet and then hide the sheet. The help I need is to remove duplicate rows from that sheet. Can it be incorporated into this code? Thank you!
Sub ImportCSVsWithReference()
'UpdatedforSPSS
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select the folder with the csv files [File Picker]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = Sheets.Add
ActiveSheet.Name = "ImportedData"
Worksheets("ImportedData").Visible = False
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
xWb.Close False
xFile = Dir
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "Encountered an error. Try again", , "Error"
End Sub
There is actually a built-in function to remove duplicates from a range. It is called RemoveDuplicates...
Let's look at an example. I assume here that -
The table has 3 columns
The table has 100 rows
The table does not have a header line
Then the code to remove duplicates will look something like:
ActiveSheet.Range("A1:C100").RemoveDuplicates Columns:=Array(1, 2, 3), Header:=xlNo
See the docs at https://learn.microsoft.com/en-us/office/vba/api/excel.range.removeduplicates
Do Not Import Headers After the First Imported Worksheet
s - Source (read from)
d - Destination (written to)
The Code
Option Explicit
Sub ImportCSVsWithReference()
Const ProcName As String = "ImportCSVsWithReference"
'On Error GoTo clearError
Const WorksheetName As String = "ImportedData"
Const HeaderRows As Long = 1
' Get Folder Path.
Dim FolderPath As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.AllowMultiSelect = False
'.InitialFileName = "C:\Test" ' consider using this
.Title = "Select the folder with the csv files [File Picker]"
If .Show = -1 Then
FolderPath = .SelectedItems(1)
Else
GoTo ProcExit ' Exit Sub
End If
End With
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Application.ScreenUpdating = False
' Define Destination Worksheet (delete existing, add new).
On Error Resume Next
Dim dws As Worksheet: Set dws = dwb.Worksheets(WorksheetName)
On Error GoTo 0
If Not dws Is Nothing Then ' it already exists
Application.DisplayAlerts = False
dws.Delete ' delete without confirmation
Application.DisplayAlerts = True
End If
Set dws = dwb.Worksheets.Add(After:=dwb.Sheets(dwb.Sheets.Count)) ' Sheets!
dws.Name = WorksheetName
dws.Visible = xlSheetHidden ' xlSheetVeryHidden (a 'tougher' option)
' Define Destination Cell.
Dim dCell As Range: Set dCell = dws.Range("A1")
' Copy data from Source Worksheets to Destination Worksheet.
Dim FileName As String: FileName = Dir(FolderPath & "\" & "*.csv")
Dim sws As Worksheet
Dim srg As Range
Dim swsCount As Long
Do While FileName <> ""
' There is only one worksheet in a csv file (the first):
Set sws = Workbooks.Open(FolderPath & "\" & FileName).Worksheets(1)
Set srg = sws.UsedRange
If srg.Rows.Count > HeaderRows Then
swsCount = swsCount + 1
If swsCount > 1 Then ' headers for the first worksheet only
Set srg = srg.Resize(srg.Rows.Count - HeaderRows) _
.Offset(HeaderRows)
End If
dCell.Resize(srg.Rows.Count, srg.Columns.Count).Value _
= srg.Value
Set dCell = dCell.Offset(srg.Rows.Count)
End If
sws.Parent.Close False ' the workbook is the 'parent' of the worksheet
FileName = Dir
Loop
'dwb.save
ProcExit:
If Application.ScreenUpdating = False Then
Application.ScreenUpdating = True
End If
' Inform.
Select Case swsCount
Case 0
MsgBox "No worksheet imported.", vbExclamation, "Fail?"
Case 1
MsgBox "1 worksheet imported.", vbInformation, "Success"
Case Else
MsgBox swsCount & " worksheets imported.", vbInformation, "Success"
End Select
Exit Sub
clearError:
MsgBox "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Sub

Combine multiple files to one sheet as values and remove filters

I would like to combine sheets with the same name & format from multiple files into a single summary sheet. I used this code to do it but I found it won't copy any filtered data or link cells. I also tried a couple codes to remove the filter, and the copied data becomes uncontinuous. Could someone look into this and help me? Thanks!
Sub Multiple_to_One()
Dim MyPath, MyName, AWbName
Dim Wb As Workbook, WbN As String
Dim G As Long
Dim Num As Long
Dim BOX As String
Dim lo As ListObject
Application.ScreenUpdating = False
MyPath = ActiveWorkbook.Path
MyName = Dir(MyPath & "\" & "*.xlsm")
AWbName = ActiveWorkbook.Name
Do While MyName <> ""
If MyName <> AWbName Then
Set Wb = Workbooks.Open(MyPath & "\" & MyName)
With Workbooks(1).ActiveSheet
Wb.Sheets(13).UsedRange.Copy .Cells(.Range("B65536").End(xlUp).Row + 1, 1)
Wb.Close False
End With
End If
MyName = Dir
Loop
MsgBox "All done.", vbInformation, "bingo"
End Sub
This is a bit of a brute force method, but seems to work:
Sub Summarize()
Dim sourcePath As String
Dim sourceName As String
Dim sourceWorkbook as Workbook ' Workbook to be copied
Dim sourceSheet as Worksheet
Dim thisWorkbookName as String
Dim copyCell as Range
Dim sourceBase as Range ' Summary starts here
Application.ScreenUpdating = False
sourcePath = ActiveWorkbook.Path
thisWorkbookName = ActiveWorkbook.Name
sourceName = Dir(MyPath & "\" & "*.xlsm")
Set sourceBase = Workbooks(1).ActiveSheet.Range("A1") ' Set to what you want
Do While sourceName <> ""
If sourceName <> thisWorkbookName Then
Set sourceWorkbook = Workbooks.Open(sourcePath & "\" & sourceName)
Set sourceSheet = sourceWorkbook.Sheets(13)
For Each copyCell In sourceSheet.UsedRange
copyCell.Copy sourceBase.Offset(copyCell.Row - 1, copyCell.Column - 1)
Next
Set sourceBase = sourceBase.Offset(sourceSheet.UsedRange.Rows.Count)
Set copyCell = Nothing
Set sourceSheet = Nothing
sourceWorkbook.Close False
End If
sourceName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "All done.", vbInformation, "bingo"
End Sub
I'm just manually copying every cell in the used range into the target sheet. The base cell gets reset after each sheet, so it should just keep appending to the target sheet.
Caveat
I've only tested the inner code in my own sheet. I made adjustments on the fly to fit everything into your original logic. The entire function above should replace your original function. If you have errors, it's because I mistyped something. My apologies.
I set the autofiltermode to False. This worked in my case.
Wb.Sheets(13).AutoFilterMode = False
Here is the modified code.
Sub Multiple_to_One()
Dim MyPath, MyName, AWbName
Dim Wb As Workbook, WbN As String
Dim G As Long
Dim Num As Long
Dim BOX As String
Dim lo As ListObject
Application.ScreenUpdating = False
MyPath = ActiveWorkbook.Path
MyName = Dir(MyPath & "\" & "*.xlsm")
AWbName = ActiveWorkbook.Name
Do While MyName <> ""
If MyName <> AWbName Then
Set Wb = Workbooks.Open(MyPath & "\" & MyName)
Wb.Sheets(13).AutoFilterMode = False
ThisWorkbook.Activate
With Workbooks(1).ActiveSheet
Wb.Sheets(13).UsedRange.Copy .Cells(.Range("B65536").End(xlUp).Row + 1, 1)
Wb.Close False
End With
End If
MyName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "All done.", vbInformation, "bingo"
End Sub

Save new file excel with filename cell value

I need to generate many .xls files
renamed as the name contained in row A1, A2, A3 ....
example: NAME1.xls, NAME2.xls ...
and the new generated file must contain only the cells contained in the markers ####
(see IMG...cellD4:T32)
the markers change manually entered by me.
I tried this code only to save new .xls files
but it does not work....I do not know how to do the rest
Private Sub CommandButton1_Clickl()
Dim path As String
Dim filename1 As String
path = "C:\"
filename1 = Range("A1").Text
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=path & filename1 & ".xls", FileFormat:=x1OpenXMLWorkbook
Application.DisplayAlerts = True
ActiveWorkbook.Close
End Sub
Okay here ya go. This should grab the chunk of the original workbook you're looking for and save it as multiple new workbooks.
Option 1 removes formatting
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim arr() As Variant
arr = wksht.Range("C3:U33").value
Dim wb As Workbook
Dim i As Long
For i = 1 To ActiveSheet.Range("A1").End(xlDown).Row
Set wb = Application.Workbooks.Add
wb.Sheets(1).Range("A1", Cells(UBound(arr), UBound(arr, 2))).value = arr
wb.SaveAs filename:=path & wksht.Range("A" & i).value & ".xlsx"
wb.Close
Next i
End Sub
Option 2 keeps formatting
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim dataRange As Range
Set dataRange = wksht.Range("C3", wksht.UsedRange.SpecialCells(xlCellTypeLastCell))
Dim wb As Workbook
Dim i As Long
For i = 1 To wksht.Range("A" & wksht.rows.count).End(xlUp).Row
Set wb = Application.Workbooks.Add
dataRange.Copy wb.Sheets(1).Range("A1", wb.Sheets(1).Cells(dataRange.rows.count, dataRange.Columns.count))
wb.SaveAs filename:=path & wksht.Range("A" & i).value & ".xlsx"
wb.Close
Next i
End Sub
but note that the starting point is still C3 based on the example given.
Option 3 keeps formatting and selects the range between the 2 cells with #### in them
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim rngeStart
Dim rngeEnd
Set rngeStart = wksht.UsedRange.Find(What:="####", LookIn:=xlValues, LookAt:=xlWhole)
Set rngeEnd = wksht.UsedRange.FindNext(After:=rngeStart)
Dim dataRange As Range
Set dataRange = wksht.Range(rngeStart, rngeEnd)
Dim wb As Workbook
Dim i As Long
For i = 1 To wksht.Range("A" & wksht.rows.count).End(xlUp).Row
Set wb = Application.Workbooks.Add
dataRange.Copy wb.Sheets(1).Range("A1", wb.Sheets(1).Cells(dataRange.rows.count, dataRange.Columns.count))
wb.SaveAs filename:=path & wksht.Range("A" & i).value & ".xlsx"
wb.Close
Next i
End Sub
Option 5 keeps row heights and column widths
Private Sub CommandButton1_Clickl()
Dim wksht As Worksheet
Set wksht = ActiveSheet
Dim path As String
path = "C:\test\"
If Len(Dir(path, vbDirectory)) = 0 Then
MkDir path
End If
Dim rngeStart
Dim rngeEnd
Set rngeStart = wksht.UsedRange.Find(What:="####", LookIn:=xlValues, LookAt:=xlWhole)
Set rngeEnd = wksht.UsedRange.FindNext(After:=rngeStart)
Dim dataRange As Range
Set dataRange = wksht.Range(rngeStart, rngeEnd)
Dim newDataRange As Range
Dim wb As Workbook
Dim i As Long
Dim j As Long
Dim k As Long
For i = 1 To wksht.Range("A" & wksht.Rows.Count).End(xlUp).Row
Set wb = Application.Workbooks.Add
Set newDataRange = wb.Sheets(1).Range("A1", wb.Sheets(1).Cells(dataRange.Rows.Count, dataRange.Columns.Count))
dataRange.Copy newDataRange
For j = 1 To dataRange.Columns.Count
newDataRange.Cells(1, j).ColumnWidth = dataRange.Cells(1, j).ColumnWidth
Next j
For k = 1 To dataRange.Rows.Count
newDataRange.Cells(k, 1).RowHeight = dataRange.Cells(k, 1).RowHeight
Next k
wb.SaveAs filename:=path & wksht.Range("A" & i).Value & ".xlsx"
wb.Close
Next i
End Sub
Try this:
Sub filename()
Dim i As Integer
For i = 1 To 32
ChDir "C:\path\"
ActiveWorkbook.SaveAs Filename:= _
"C:\path\" & Range("A" & i).Value & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Next i
End Sub
Note: Don't use "C:\" choose another folder. Probably you will need admin permissions to save there.

Resources