Workbook Scraper Issue - excel

I have been working on a workbook that scrapes data from hundreds of other workbooks and it works fine. However, when an error occurs, the workbook that has the error opens in the background and since this happens numerous times, my computer freezes before it can get through all the workbooks. Is there a way to suppress all link issue prompts and close workbooks that have errors instead of having them remain open? Here is the code that I have that works great for small sets of workbooks (I have done 10 without issue):
Sub CopyRange()
Application.ScreenUpdating = False
Dim wkbDest As Workbook, sh As Worksheet
Dim wkbSource As Workbook
Set wkbDest = ThisWorkbook
Dim LastRow As Long
'you need to create this worksheet named "Log"
Dim LogSheet As Worksheet
Set LogSheet = ThisWorkbook.Worksheets("Log")
Const strPath As String = "E:\Desktop\Example\"
ChDir strPath
strExtension = Dir(strPath & "*.xls*")
Application.StatusBar = "Importing Data..."
Do While strExtension <> ""
path = strPath & strExtension
If VerifyTasks(strPath & strExtension, wkbDest) Then
LogSheet.Range("A" & LogSheet.Rows.Count).End(xlUp).Offset(1, 0).Value = strPath & strExtension & " " & "Succeeded"
Else
LogSheet.Range("A" & LogSheet.Rows.Count).End(xlUp).Offset(1, 0).Value = strPath & strExtension & " " & "Failed"
End If
On Error GoTo 0
strExtension = Dir
Loop
Application.ScreenUpdating = True
Application.StatusBar = False
MsgBox "Data imported, review Log sheet."
End Sub
Function VerifyTasks(path As String, ByRef wkbDest As Workbook) As Boolean
On Error GoTo errorhandler:
Set wkbSource = Workbooks.Open(path)
With wkbSource
'locate last row to start copying new value from the next spreadsheet
LastRow = wkbDest.Sheets("Master").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Row
'From the Basis & Credits cell AB46, copy to last row+1 in the Master sheet starting in row A2
.Sheets("Basis & Credits").Range("AB46").Copy
wkbDest.Sheets("Master").Range("A" & LastRow).PasteSpecial Paste:=xlPasteValues
.Close savechanges:=False
End With
VerifyTasks = True
Exit Function
errorhandler:
VerifyTasks = False
End Function
Thank you.

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

Excel crashing when I run VBA macro

I have a workbook with a VBA macro that I run every day where I paste a large set of data and it formats, fills in extra fields using a vlookup against hidden sheets, splits the data into individual sheets, and saves each as a CSV file.
This process runs perfectly 6 out 7 days of the week & only has issues when I run Sunday data.
All VBA macros within the workbook work fine until I get to the step where it saves the CSVs, then it force closes the excel workbook.
I've noticed it saves 1 worksheet (named RCM), but even that it does incorrectly as it only pulls the first row into the file, and the row is from the incorrect sheet.
I thought the issue was with the sheet name (as I have a hidden sheet named RCM1 and the hidden sheets do not get saved). But I've attempted renaming the sheets & am still having the same issue.
I'm now uncertain of what is causing Excel to crash only with this particular data.
Here is the save portion of the macro
Sub SaveSheets()
'
' SaveSheets Macro
' Saves sheets as individual CSV files
'
'
Dim csvPath As String
Dim DateName As String
csvPath = "C:\Daily Batch Files"
r = Worksheets("Data").Range("B2")
DateName = "batchredeem.001." & WorksheetFunction.Text(r, "mmmmdd") & "_"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Work").ShowAllData
For Each xWs In ThisWorkbook.Sheets
If xWs.Visible = xlSheetVisible And xWs.Name <> "Magic Buttons" And xWs.Name <> "Data" And xWs.Name <> "Work" Then
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=csvPath & "\" & DateName & xWs.Name & ".csv", FileFormat:=xlCSV
Application.ActiveWorkbook.Close False
ElseIf xWs.Name = "Work" Then
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=csvPath & "\" & xWs.Name & ".csv", FileFormat:=xlCSV
Application.ActiveWorkbook.Close False
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
**EDIT to add additional info:
If I change the name of the sheet before running the macro, it won't save the renamed "RCM" sheet at all- it works for the previous sheet, however, and if I delete the "RCM" sheet, the entire macro runs normally.
***EDIT 2 - I also cannot manually "copy" the "RCM" sheet, but I can manually copy any of the others. Also, if I save the entire workbook, then run the macro, it works normally! I'm stumped & not sure why it isn't working just for this one worksheet.
Export Worksheets As One-Worksheet Files
Option Explicit
Sub ExportVisibleWorksheets()
' Saves worksheets as individual CSV files
' Source
Const sExceptionsList As String = "Magic Buttons,Work,Data"
Const sSpecialName As String = "Work" ' exported differently
' Source Lookup
Const slName As String = "Data" ' included in the exceptions list
Const slCellAddress As String = "B2"
' Destination
Const dDateLeft As String = "batchredeem.001."
Const dDateMidFormat As String = "mmmmdd"
Const dDateRight As String = "_"
Dim dFolderPath As String: dFolderPath = "C:\Daily Batch Files\"
' The following two depend on each other!
Dim dFileExtension As String: dFileExtension = ".csv"
Dim dFileFormat As XlFileFormat: dFileFormat = xlCSV
If Right(dFolderPath, 1) <> "\" Then dFolderPath = dFolderPath & "\"
If Len(Dir(dFolderPath, vbDirectory)) = 0 Then Exit Sub ' doesn't exist
If Left(dFileExtension, 1) <> "." Then dFileExtension = "." & dFileExtension
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets(slName)
Dim sCell As Range: Set sCell = sws.Range(slCellAddress)
Dim sExceptions() As String: sExceptions = Split(sExceptionsList, ",")
Dim dDateMid As String
dDateMid = WorksheetFunction.Text(sCell.Value, dDateMidFormat) ' English
'dDateMid = Format(sCell.Value, dDateMidFormat) ' International
Dim dDateName As String: dDateName = dDateLeft & dDateMid & dDateRight
Application.ScreenUpdating = False
Dim dwb As Workbook
Dim dFilePath As String
Dim dwsCount As Long
Dim ErrNum As Long
Dim DoNotCopy As Boolean
For Each sws In swb.Worksheets
If sws.Visible = xlSheetVisible Then
If IsError(Application.Match(sws.Name, sExceptions, 0)) Then
dFilePath = dFolderPath & dDateName & sws.Name & dFileExtension
ElseIf StrComp(sws.Name, sSpecialName, vbTextCompare) = 0 Then
dFilePath = dFolderPath & sws.Name & dFileExtension
If sws.AutoFilterMode Then
sws.ShowAllData
End If
Else
DoNotCopy = True
End If
If DoNotCopy Then
DoNotCopy = False
Else
sws.Copy
Set dwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite: no confirmation
On Error Resume Next ' prevent error if file is open
dwb.SaveAs Filename:=dFilePath, FileFormat:=dFileFormat
ErrNum = Err.Number
On Error GoTo 0
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False
If ErrNum = 0 Then
dwsCount = dwsCount + 1
Else
ErrNum = 0
End If
End If
End If
Next
Application.ScreenUpdating = True
Select Case dwsCount
Case 0: MsgBox "No worksheets exported.", vbExclamation
Case 1: MsgBox "One visible worksheet exported.", vbInformation
Case Else
MsgBox dwsCount & " visible worksheets exported.", vbInformation
End Select
End Sub

VBA to copy workbook and keep relative cell references between sheets

I have workbook that has multiple sheets and need a macro button to save a copy of it and delete the sheet named "CSG". This was easy to do, but the problem was that all cell references pointed to the original workbook.
With help, the problem has been tried to solve through name manager and break all links-code. Now the problem is that it break all references within the new workbook and copies only the values from the original workbook.
For example, in the original workbook sheet1 cell A1 has value 10, sheet2 cell A1 has cell reference "='sheet1'!A1". When I make the new copy, both cells do have the value 10, but the reference is no longer there.
Is there a way to keep these references within the workbook without them referencing the original workbook? Below is the code currently being used.
Sub SaveTest()
Dim x As Integer
Dim FileName As String, FilePath As String
Dim NewWorkBook As Workbook, OldWorkBook As Workbook
Set OldWorkBook = ThisWorkbook
With Application
.ScreenUpdating = False: .DisplayAlerts = False
End With
On Error Resume Next
With OldWorkBook.Sheets("CSG")
FilePath = "C:\Users\Tom\Desktop\" & .Range("B1").Value & " " & .Range("B2").Value
FileName = .Range("B1").Value & " " & .Range("B2").Value & ".xlsx"
End With
MkDir FilePath
On Error GoTo -1
On Error GoTo myerror
FilePath = FilePath & "\"
For x = 2 To OldWorkBook.Worksheets.Count
With OldWorkBook.Worksheets(x)
If Not NewWorkBook Is Nothing Then
.Copy after:=NewWorkBook.Worksheets(NewWorkBook.Worksheets.Count)
Else
.Copy
Set NewWorkBook = ActiveWorkbook
End If
End With
Next x
DeleteBadNames NewWorkBook
BreakAllLinks NewWorkBook
UpdateNameManager NewWorkBook
NewWorkBook.SaveAs FilePath & FileName, 51
myerror:
If Not NewWorkBook Is Nothing Then NewWorkBook.Close False
With Application
.ScreenUpdating = True: .DisplayAlerts = True
End With
If Err <> 0 Then MsgBox (Error(Err)), 48, "Error"
End Sub
Create a Copy of a Workbook
Option Explicit
Sub SaveTest()
Dim OldWorkBook As Workbook: Set OldWorkBook = ThisWorkbook
Dim WorkSheetNames() As String
Dim FilePath As String
Dim FileName As String
With OldWorkBook.Worksheets("CSG")
ReDim WorkSheetNames(1 To .Parent.Worksheets.Count)
FilePath = "C:\Users\Tom\Desktop\" & .Range("B1").Value & " " _
& .Range("B2").Value
FileName = .Range("B1").Value & " " & .Range("B2").Value & ".xlsx"
End With
On Error Resume Next
MkDir FilePath
On Error GoTo 0
FilePath = FilePath & "\"
Dim ws As Worksheet
Dim n As Long
For Each ws In OldWorkBook.Worksheets
n = n + 1
WorkSheetNames(n) = ws.Name
Next ws
Application.ScreenUpdating = False
OldWorkBook.Worksheets(WorkSheetNames).Copy
With ActiveWorkbook ' new workbook
Application.DisplayAlerts = False
.Worksheets("CSG").Delete
.SaveAs FilePath & FileName, 51 ' xlOpenXMLWorkbook
Application.DisplayAlerts = True
'.Close SaveChanges:=False
End With
Application.ScreenUpdating = True
End Sub

Continue pasting data in successive worksheets when the current workhseet's row limit exceeds 1,048,576

The macro I wrote copies some data from several .dat files to a specific worksheet. It works fine as long as the number of records don't exceed the maximum 1,048,576 rows in my worksheet(excel 2016). How to modify the code to continue pasting data from the source file to the successive worksheets when the max row of 1,048,576 is exceeded?
I first tried to paste data from each source file in individual worksheets in my workbook. But that would create so many sheets in the workbook which I don't want. I want my data to be in minimum number of worksheets as possible.
Sub KLT()
Dim StartTime As Double
Dim MinutesElapsed As String
Dim wbA As Workbook, wbB As Workbook
Dim button_click As VbMsgBoxResult
Dim myPath As String, myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim count As Integer
Dim LIST As Integer
Dim xWs As Worksheet
Dim sh As Worksheet
Dim xcount As Integer
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
On Error Resume Next
'Remember time when macro starts
StartTime = Timer
'Deleting the "Start" sheet from previous macro run
For Each xWs In Application.Worksheets
If xWs.Name = "Start" Then
xWs.Delete
End If
Next
'Adding a new Sheet called "Start"
Worksheets.Add(After:=Worksheets(Worksheets.count)).Name = "Start"
Set wbA = ThisWorkbook
Set sh = wbA.Sheets("Start")
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.DAT*" 'my data is in .dat files
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension) 'Storing the actual raw file name
'Loop through each Excel file in folder
Execute:
Do While myFile <> ""
'Set variable equal to opened workbook
Set wbB = Workbooks.Open(Filename:=myPath & myFile)
'The source file range might be a continuation of a previous file, so ensuring the correct range is identified always
If wbB.ActiveSheet.Range("A1").Value = "Continuation of previous file." Then Range("A1").EntireRow.Delete
'Filtering data set and choosing data below headers
With wbB.ActiveSheet
.AutoFilterMode = False
With Range("A1", Range("A" & Rows.count).End(xlUp)) 'I am only interested in the data below the header
.AutoFilter 1, "*Cycle*"
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
.AutoFilter 1, "*Profile*"
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
'Choosing the desired range to be copied
Set Rng = Union _
(Range("A2", Range("A2").End(xlDown)), _
Range("D2", Range("D2").End(xlDown)), _
Range("E2", Range("E2").End(xlDown)), _
Range("AX2", Range("AX2").End(xlDown)))
'Rng.Select
'''Copying relevant information from the source file & pasting in the Start worksheet'''
lr = sh.Range("A" & Rows.count).End(xlUp).Row + 1
Rng.Copy sh.Range("A" & lr)
'Keeping the count of how many files have been worked on
If InStr(1, ActiveSheet.Name, "LifeCyc") > 0 Then xcount = xcount + 1
'Debug.Print xcount
''''''''***********''''''''
'Close Workbook
wbB.Close 'SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Creating the headers in my report sheet
With sh
.Range("A1").Value = "Date"
.Range("B1").Value = "CumSec"
.Range("C1").Value = "LifeCycleNo"
.Range("D1").Value = "dT"
End With
'Formatting the headers
With sh.Range("A1:D1")
.Interior.Color = rgbBlue
.LineStyle = xlContinuous
.Borders.Color = rgbBlack
.HorizontalAlignment = xlCenter
.Font.Bold = True
.Font.Color = rgbWhite
End With
'Formatting the actual dataset
With sh.Range("A2:D2", Range("A2:D2").End(xlDown))
.LineStyle = xlContinuous
.Borders.Color = rgbBlack
End With
Columns("A:D").AutoFit
'Determine how long the code took to run
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
'Displaying a message on the screen after completion of the task
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes " & "Total Raw Files Processed: " & CStr(xcount), vbInformation
'Reset Macro Optimization Settings
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = False
Application.AutomationSecurity = lSecurity
End Sub
Expected outcome is to continue pasting data in successive sheets whenever the current worksheet's row number exceeds the max limit
I am not convinced that it is a good idea to let Excel handle such an amount of data, and I am not sure how you want to deal with more than one sheet having data...
Remove On Error Resume Next. It will hide all errors and you will never recognize that your code had a problem.
Set your wbA-variable at the beginning and work with that, not with then Application.Worksheets object.
Introduce a sheet-counter variable.
Before copying the Range, check if you have enough space left, else create the next sheet.
Do the formatting for all sheets.
Code could look like this (untested, may contain syntax errors)
const SHEETNAME = "Start"
Set wbA = ThisWorkbook
For Each xWs In wbA.Worksheets
If xWs.Name like SHEETNAME & "*" Then
xWs.Delete
End If
Next xWs
dim sheetCount as Long
sheetCount = 1
set sh = wbA.Worksheets.Add(After:=wbA.Worksheets(wbA.Worksheets.count))
sh.Name = SHEETNAME & sheetCount
(...)
lr = sh.Range("A" & Rows.count).End(xlUp).row + 1
If lr + rng.rows.count > sh.Rows.count then
' Not enough space left, add new sheet.
sheetCount = sheetCount + 1
set sh = wbA.Worksheets.Add(After:=sh)
sh.Name = SHEETNAME & sheetCount
lr = 1
End if
rng.Copy sh.Range("A" & lr)
(...)
' Format all data sheets.
For Each xWs In wbA.Worksheets
with xWs
If .Name like SHEETNAME & "*" Then
.Range("A1").Value = "Date"
(...)
' Create a table
lr = .Range("A" & Rows.count).End(xlUp).row
.ListObjects.Add(xlSrcRange, .Range("$A$1:$D$" & lr), , xlYes).Name = "Table_" & .Name
End If
End With
Next xWs

Copying collections of sheets identified by name list to new workbooks

I am trying to copy specific collections sheets within an excel workbook in separate workbooks. Not being a vba coder I have used and adapted code found here and other resource sites. I believe I am now very close having grasped the basic concepts but cannot figure out what i am doing wrong, triggering the below code causes the first new workbook to be created and the first sheet inserted but breaks at that point.
My code is below, additional relevant info - there is a sheet called 'List' which has a column of names. Each name on the list has 2 sheets which I am trying to copy 2 by 2 into new sheet of the same name. the sheets are labelled as the name and the name + H (e.g Bobdata & BobdataH)
Sub SheetCreate()
'
'Creates an individual workbook for each worksname in the list of names.
'
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sht As Object
Dim strSavePath As String
Dim sname As String
Dim relativePath As String
Dim ListOfNames As Range, LRow As Long, Cell As Range
With ThisWorkbook
Set ListSh = .Sheets("List")
End With
LRow = ListSh.Cells(Rows.Count, "A").End(xlUp).Row '--Get last row of list.
Set ListOfNames = ListSh.Range("A1:A" & LRow) '--Qualify list.
With Application
.ScreenUpdating = False '--Turn off flicker.
.Calculation = xlCalculationManual '--Turn off calculations.
End With
Set wbSource = ActiveWorkbook
For Each Cell In ListOfNames
sname = Cell.Value & ".xls"
relativePath = wbSource.Path & "\" & sname
Sheets(Cell.Value).Copy
Set wbDest = ActiveWorkbook
Application.DisplayAlerts = False
ActiveWorkbook.CheckCompatibility = False
ActiveWorkbook.SaveAs Filename:=relativePath, FileFormat:=xlExcel8
Application.DisplayAlerts = True
wbSource.Activate
Sheets(Cell.Value & "H").Copy after:=Workbooks(relativePath).Sheets(Cell.Value)
wbDest.Save
wbDest.Close False
Next Cell
MsgBox "Done!"
End Sub
You can try to change
Sheets(Cell.Value & "H").Copy after:=Workbooks(relativePath).Sheets(Cell.Value)
to
Sheets(Cell.Value & "H").Copy after:=wbDest.Sheets(Cell.Value)
Also it would be good idea to check if file already exists in selected location. For this you can use function:
Private Function findFile(ByVal sFindPath As String, Optional sFileType = ".xlsx") As Boolean
Dim obj_fso As Object: Set obj_fso = CreateObject("Scripting.FileSystemObject")
findFile = False
findFile = obj_fso.FileExists(sFindPath & "/" & sFileType)
Set obj_fso = Nothing
End Function
and change sFileType = ".xlsx" to "*" or other excet file type.
This was the code i created to create a new workbook and then copy sheet contents from existing one to the new one. Hope it helps.
Private Sub CommandButton3_Click()
On Error Resume Next
Application.ScreenUpdating = False
Application.DisplayAlerts = False
TryAgain:
Flname = InputBox("Enter File Name :", "Creating New File...")
MsgBox Len(Flname)
If Flname <> "" Then
Set NewWkbk = Workbooks.Add
ThisWorkbook.Sheets(1).Range("A1:J100").Copy
NewWkbk.Sheets(1).Range("A1:J100").PasteSpecial
Range("A1:J100").Select
Selection.Columns.AutoFit
AddData
Dim FirstRow As Long
Sheets("Sheet1").Range("A1").Value = "Data Recorded At-" & Format(Now(), "dd-mmmm-yy-h:mm:ss")
NewWkbk.SaveAs ThisWorkbook.Path & "\" & Flname
If Err.Number = 1004 Then
NewWkbk.Close
MsgBox "File Name Not Valid" & vbCrLf & vbCrLf & "Try Again."
GoTo TryAgain
End If
MsgBox "Export Complete Close the Application."
NewWkbk.Close
End If
End Sub

Resources