VBA Script to split all worksheets in a workbook to separate files - vba

I have a script that does a vlookup for each sheet in workbook and then splits each worksheet into its own file. I have the below script, but it is not working. The vlookup portion is working fine, but I am having issues with the split. It doesn't fail and give me an error, it just doesn't do anything.
Sub Splitbook()
MyPath = "***Folder Location***"
For Each sht In Workbooks("PO135 Division 1.xlsx").Worksheets
sht.Copy
ActiveSheet.Cells.Copy
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats
ActiveWorkbook.SaveAs _
Filename:=MyPath & "\" & sht.Name & ".xlsx"
ActiveWorkbook.Close savechanges:=False
Next sht
End Sub
I need to split the files and then save them in a distinct folder("Folder Location")--this is just a placeholder for the time being, it would be updated prior to running the script--
Any thoughts? Appreciate the help!

Put this in a regular module:
Sub NewWb()
Dim ws As Worksheet
Dim wbActive As Workbook
Dim wbNew As Workbook
Dim x As Single
Application.ScreenUpdating = False
Set wbActive = ActiveWorkbook
For Each ws In wbActive.Worksheets
Set wbNew = Workbooks.Add
ws.Copy Before:=wbNew.Sheets(1)
abc = "C:\Files\" & ws.Name & ".xlsx"
Application.DisplayAlerts = False
wbNew.Sheets("Sheet1").Delete
Application.DisplayAlerts = True
wbNew.SaveAs Filename:=abc
wbNew.Close Saved = True
Next ws
Set ws = Nothing
Set wbActive = Nothing
Set wbNew = Nothing
Application.ScreenUpdating = True
End Sub

Related

How to run VBA in excel, when Excel filename got changed

I have a Workbook (1) contains 2 sheets. In my program, I would like to generate a workbook (2) which Create 2 sheets. Then the program will filter the table and copy values from workbook 1 to workbook 2.
But my problem is my workbook (1) name will get changed every time. I tried to use ActiveWorkbook.Name. But when the program is running, it will create a new workbook then suddenly it became an active workbook.
I named my main Workbook (1) as Filevalue. But not working. How to solve this problem. I need to run this program eventhough when the name get changed. Help me
Sub createlandDE()
Filepath = ActiveWorkbook.path
FileValue = ActiveWorkbook.Name 'Problem With Activeworkbook
NameValue = Format(Date, "yymmdd") & "-DE"
Dim wb As Workbook
Set wb = Workbooks.add
Dim path As String
Dim FSO As Object
path = Filepath & "\" & NameValue & ".xlsx"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(path) Then
On Error Resume Next
Workbooks(NameValue & ".xlsx").Close False
Kill path
wb.SaveAs path
Sheets(3).Delete
Else
wb.SaveAs path
Sheets(3).Delete
End If
Application.ScreenUpdating = False
Dim ws, ws1, ws2 As Worksheet
Dim table1, table2 As ListObject
Dim rng1 As Range
Sheets(1).Name = "Main view"
Sheets(2).Name = "Overall view"
Set ws1 = Workbooks(NameValue & ".xlsx").Worksheets("Main view")
ws1.ListObjects.add(xlSrcRange, ws1.Range("A$1:$J$1"), , xlYes).Name = "MainTable"
Set table1 = ws1.ListObjects(1)
Set ws = Workbooks(FileValue).Worksheets("Main") 'Problem With Activeworkbook
ws.PivotTables("MainTable").PivotFields("Dealer Country Code").CurrentPage = "DE"
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set rng1 = Range(.Range("A4"), .Range("J" & LastRow))
End With
rng1.Copy
ws1.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Set ws2 = Sheets("Overall view")
ws2.ListObjects.add(xlSrcRange, ws2.Range("A$1:$Q$1"), , xlYes).Name = "OverallTable"
Set table2 = ws2.ListObjects(1)
Worksheets("Overall view").ListObjects("OverallTable").TableStyle = "Table Style 1"
Workbooks(FileValue).Activate 'Problem With Activeworkbook
Sheet2.ListObjects("DataTable").Range.AutoFilter Field:=1
Sheet2.ListObjects("DataTable").Range.AutoFilter Field:=12
ActiveWorkbook.Save
Application.ScreenUpdating = True
End Sub

Paste Special Error - 1004 VBA Excel

I am trying to create a loop to copy data in cells in source worksheet one by one and paste in a particular cell in target worksheet. Once the cell is pasted, i need it to save a copy of the file then paste the next value in the source worksheet.The code is:
Private Sub CommandButton1_Click()
Dim wbTarget As Worksheet
Dim wbSource As Worksheet
Dim SaveLoc As String
Dim FName As String
Dim i As Long
Set wbSource = Sheets("Sheet3")
Set wbTarget = Sheets("Sheet1")
wbSource.Activate
Range("A1").Activate
Do While ActiveCell.Value <> ""
DoEvents
ActiveCell.Copy
For i = 1 To 30
wbTarget.Activate
With ActiveSheet
wbTarget.Range("E5").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths
Selection.PasteSpecial Paste:=xlPasteValues
ThisWorkbook.Save
Application.CutCopyMode = False
End With
SaveLoc = "H:\Services\Test Output\Term_"
FName = Range("B5")
ActiveWorkbook.SaveCopyAs FileName:=SaveLoc & FName & ".xls" 'FileFormat:=xlNormal
Application.DisplayAlerts = False
Next i
wbSource.Select
ActiveCell.Offset(1, 0).Activate
Loop
Application.ScreenUpdating = True
End Sub
When I run this, I get a
run-time error 1004.
Please advise on how to resolve this.
Thank You in Advance.
Try the code below, without using Activate, ActiveCell, Select and Selection, instead use fully qualifies Ranges and Worksheet objects.
Explanation inside the code as comments (also some question about your code).
Code
Option Explicit
Private Sub CommandButton1_Click()
Dim wbTarget As Worksheet
Dim wbSource As Worksheet
Dim SaveLoc As String
Dim FName As String
Dim i As Long, lRow As Long
Set wbSource = Sheets("Sheet3")
Set wbTarget = Sheets("Sheet1")
' SaveLoc string never changes, doesn;t need to be set every time inside the loops
SaveLoc = "H:\Services\Test Output\Term_"
' you never qualifed the range with on of the worksheets (I'm guessing here it's "Sheet3"
FName = wbTarget.Range("B5").Value
Application.ScreenUpdating = False
lRow = 1
Do While wbSource.Range("A" & lRow).Value <> ""
wbSource.Range("A" & lRow).Copy
For i = 1 To 30
' 2 lines below you are pasting to cell "E5" don't you mean to increment with the row number (i variable)
wbTarget.Range("E5").PasteSpecial xlPasteValues
wbTarget.Range("E5").PasteSpecial xlPasteColumnWidths
ThisWorkbook.Save
Application.CutCopyMode = False
' have this line before trying to save a copy of this workbook
Application.DisplayAlerts = False
ThisWorkbook.SaveCopyAs Filename:=SaveLoc & FName & ".xls" 'FileFormat:=xlNormal
Application.DisplayAlerts = True
Next i
lRow = lRow + 1
Loop
Application.ScreenUpdating = True
End Sub

Split Excel Sheet from one Excel file to Multiple Excel file

Sub Splitbook()
MyPath = ThisWorkbook.Path
For Each sht In ThisWorkbook.Sheets
sht.Copy
ActiveSheet.Cells.Copy
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats
ActiveWorkbook.SaveAs _
Filename:=MyPath & "\" & sht.Name & ".xlsx"
ActiveWorkbook.Close savechanges:=True
Next sht
End Sub
It is giving an error
Runtime error 1004
Copy method of worksheet class failed
How can i remove this error?
Test code using objects to handle the copy properly:
Sub Splitbook()
Dim MyPath As String
Dim ShT As Worksheet
Dim NewWB As Workbook
Dim NewSHT As Worksheet
MyPath = ThisWorkbook.Path
For Each ShT In ThisWorkbook.Sheets
ShT.Copy
Set NewWB = ActiveWorkbook
With NewWB
With .Sheets(1)
With .Cells
.Copy
.PasteSpecial Paste:=xlPasteValues
.PasteSpecial Paste:=xlPasteFormats
End With '.Cells
End With '.Sheets(1)
.SaveAs FileName:=MyPath & "\" & ShT.Name & ".xlsx"
.Close savechanges:=True
End With 'NewWB
Next ShT
End Sub
Sub Splitbook()
MyPath = ThisWorkbook.Path
For Each sht In ThisWorkbook.Sheets
sht.usedrange.copy
set wb= workbooks.add
wb.sheets(1).Paste
application.cutcopymode=false
wb.saveas(filename:=MyPath & "_" & sht.Name & ".xlsx",xlopenXMLworkbook)
wb.close
Next sht
End Sub
try this subroutine this might work. I havent tested the code. Please forgive me if there are any bugs.

Excel Macro: Replace formulas and save sheet as own file without changing original document

I have a workbook with a lot of worksheets. I only work on sheets marked with a !. I want to replace all formulas by values and store the sheets as own .xls files. My script is exactly doing that. My problem is that the original document is affected as well. Is there a way to replace the values only on the copied sheet which will be stored so the original document stays the same?
Dim wbk As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cl As Object
Dim xPath As String
Dim isReadable As Boolean
Dim sName As String
xPath = Application.ActiveWorkbook.Path
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
On Error Resume Next
Set wbk = ActiveWorkbook
For Each ws In wbk.Sheets
isReadable = (InStr(ws.Name, "!")) > 0
If isReadable Then
Debug.Print ws.Name
Set rng = ws.Range("A1").SpecialCells(xlCellTypeFormulas, 23)
If Not (rng Is Nothing) Then
For Each cl In rng
cl.Value = cl.Value
Next cl
End If
sName = Replace(ws.Name, "!", "")
sName = LCase(Replace(sName, "+", ""))
ws.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & sName & ".xlsx", CreateBackup:=False
Application.ActiveWorkbook.Close False
Debug.Print sName
End If
Next ws
Application.Calculate
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
MsgBox "Done, do not save the changes!"
Make a copy of the sheet and work on that:
Sub DoStuff()
Dim wsOrig As Worksheet
Dim wsNew As Worksheet
Dim wbOrig As Workbook
Dim wbNew As Workbook
Set wsOrig = ActiveSheet ' or whatever
Set wbOrig = ActiveWorkbook ' or whatever
For s = 1 To wbOrig.Sheets.Count
If wbOrig.Sheets(s) ' meets my conditions then....
Application.SetWarnings False ' don't question if we want to delete thinsg
Set wbNew = Workbooks.Add
wsOrig.Copy After:=wbNew.Sheets(1)
wbNew.Sheets(1).Delete ' delete the default Sheet1 of the new workbook
Set wsNew = wbNew.Sheets(1)
With wsNew
' do all the stuff I want to do
End With
wbNew.SaveAs ' whatever
Application.SetWarnings True
End If
Next s
End Sub
Here is another way to make the changes only on the copied sheet:
Dim ws As Worksheet, ws2 As Worksheet
For Each ws In Worksheets
If ws.Name Like "*!*" Then
ws.Copy
Set ws2 = Workbooks(Workbooks.Count).Sheets(1) ' newest workbook
ws2.Name = LCase(Replace(Replace(ws.Name, "!", ""), "+", ""))
ws2.UsedRange.Value = ws2.UsedRange.Value
ws2.Parent.SaveAs ws.Parent.Path & "\" & sName & ".xlsx", CreateBackup:=False ' add checks if the file already exist and if path contains illegal characters that are not allowed
ws2.Parent.Close False
End If
Next

Export multiple worksheets to CSV and specify save folder

I've got this Macro working beautifully, but every now and again it will save the exported sheets into the last folder I was working in, and not the specific folder I want them in. How do I specify the folder they should go into?
Sub asdf()
Dim ws As Worksheet, newWb As Workbook
Application.ScreenUpdating = False
For Each ws In Sheets(Array("sheet1", "sheet2", "sheet3"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs ws.Name & ".csv", xlCSVWindows
.Close (False)
End With
Next ws
Application.ScreenUpdating = True
End Sub
You need to specify the location you want it saved to in the code.
Try this.
.SaveAs FileName:="C:\OutputFilepath\" & ws.Name & ".csv", FileFormat:=xlCSV, CreateBackup:=False
Replace this line
.SaveAs ws.Name & ".csv", xlCSVWindows
With
.SaveAs "D:\MyFolder\" & ws.Name & ".csv", xlCSVWindows
Change the "D:\MyFolder\" to your desired path.
Add a string type var that contains the full path to the folder. In the following example, I'll use the temp directory.
Sub asdf()
Dim ws As Worksheet, newWb As Workbook, fp as string
fp = environ("TEMP") & Chr(92)
'could be something like
'fp = environ("USER") & "\desktop\"
Application.ScreenUpdating = False
For Each ws In Sheets(Array("sheet1", "sheet2", "sheet3"))
ws.Copy
Set newWb = ActiveWorkbook
With newWb
.SaveAs fp & ws.Name, xlCSVWindows 'add the path, let saveas add the extension
.Close savechanges:=False
End With
Next ws
Application.ScreenUpdating = True
End Sub