Rebuild a workbook with VBA - vba

I am trying to run the below VBA that I found online. The purpose of the code is to copy the data from all of the worksheets in a workbook to a different workbook. A couple key points:
1) I am trying to copy the data in all worksheets NOT the actual worksheets to the new workbook
2) The macro does a lot: makes sure you have a back-up file; creates a new worksheet (TargetWorkbook) and saves with the source workbook's name; etc. however, the most important part (and where I believe it is erroring) is copying the worksheets
3) I understand what is going on with the code but not savvy enough to make it work.
Sub Update_SmartView_Workbook()
' Copies sheets from a source workbook to new and current Excel target workbook to
' get rid of the "2003 or earlier backbone" that interferes with SmartView.
' Keyboard Shortcut: Ctrl+z
' Copyleft 2013 By MJ Henderson. No rights reserved. Free and worth every penny.
' User assumes all risk. No warranties implied or otherwise.
Dim ConfirmBackup As Integer
Dim SourceWorkbook, TargetWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim SourceWorkbookName As String
' User must make a backup before proceeding.
ConfirmBackup = MsgBox("Have you made a backup copy of the source file?", vbYesNo, "Confirm Backup")
If ConfirmBackup = vbNo Then
MsgBox "Try again when you have a backup copy of the source file", vbOKOnly, "Backup Required"
Exit Sub
End If
' Find and open the source file
Application.FindFile
Set SourceWorkbook = ActiveWorkbook
SourceWorkbookName = ActiveWorkbook.Name
SourceWorkbookDirectoryPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(SourceWorkbookName))
' Create a new target workbook in the same folder as the source workbook
Workbooks.Add
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx", _
FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=True
' Copy each worksheet in SourceWorkbook to TargetWorkbook THIS IS WHERE THE FIX IS NEEDED
SourceWorkbook.Activate
For Each SourceWorksheet In SourceWorkbook.Worksheets
SourceWorksheet.Cells.Copy
Windows("TargetWorkbook.xlsx").Activate
ActiveWindow.WindowState = xlNormal
On Error Resume Next
TargetWorkbook.Sheets(SourceWorksheet.Name).Delete
Range("A1").Select
ActiveSheet.Paste
Range("A1").Select
ActiveSheet.Name = SourceWorksheet.Name
Application.CutCopyMode = cancel
Next
' Close SourceWorkbook, rename SourceWorkbook with suffix "_OLD"
SourceWorkbook.Activate
SourceWorkbook.Saved = True
SourceWorkbook.Close SaveChanges:=False
Name SourceWorkbookDirectoryPath & SourceWorkbookName As SourceWorkbookDirectoryPath & SourceWorkbookName & "_OLD"
' Global replace to remove any references to old workbook. (Fixes interbook links.)
Cells.Replace What:="[" & SourceWorkbookName & "]", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
' Rename TargetWorkbook as SourceWorkbook's original name, delete TargetWorkbook
TargetWorkbook.Activate
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & SourceWorkbookName, _
FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Saved = True
ActiveWorkbook.Close SaveChanges:=False
Kill SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx"
End Sub
I believe these lines are driving the error:
Windows("TargetWorkbook.xlsx").Activate
ActiveWindow.WindowState = xlNormal
The error I am getting is "Run Time Error 9 - Subscript out of Range"
Any idea on how to fix?

Use Workbooks("TargetWorkbook.xlsx").Activate instead of Windows...

I would recommend to eliminate the activating if the sheet and workbooks; we do not need it. Just referencing the object is enough.
This is an untested code see how it goes you might need to change it a little bit to fit your needs.
Option Explicit
Sub Test()
Dim ConfirmBackup As Integer
Dim SourceWorkbook, TargetWorkbook As Workbook
Dim SourceWorksheet As Worksheet
Dim SourceWorkbookName As String
Dim SourceWorkbookDirectoryPath As String
' User must make a backup before proceeding.
ConfirmBackup = MsgBox("Have you made a backup copy of the source file?", vbYesNo, "Confirm Backup")
If ConfirmBackup = vbNo Then
MsgBox "Try again when you have a backup copy of the source file", vbOKOnly, "Backup Required"
Exit Sub
End If
' Find and open the source file
Application.FindFile
Set SourceWorkbook = ActiveWorkbook
SourceWorkbookName = ActiveWorkbook.Name
SourceWorkbookDirectoryPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(SourceWorkbookName))
' Create a new target workbook in the same folder as the source workbook
Workbooks.Add
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx", _
FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=True
' Copy each worksheet in SourceWorkbook to TargetWorkbook THIS IS WHERE THE FIX IS NEEDED
For Each SourceWorksheet In SourceWorkbook.Worksheets
TargetWorkbook.Sheets(SourceWorksheet.Name).Delete
SourceWorksheet.Copy After:=TargetWorkbook.Sheets(TargetWorkbook.Sheets.Count)
Next
' Close SourceWorkbook, rename SourceWorkbook with suffix "_OLD"
SourceWorkbook.Close SaveChanges:=True
Name SourceWorkbookDirectoryPath & SourceWorkbookName As SourceWorkbookDirectoryPath & SourceWorkbookName & "_OLD"
' Global replace to remove any references to old workbook. (Fixes interbook links.)
Cells.Replace What:="[" & SourceWorkbookName & "]", _
Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
False, SearchFormat:=False, ReplaceFormat:=False
' Rename TargetWorkbook as SourceWorkbook's original name, delete TargetWorkbook
ActiveWorkbook.SaveAs _
Filename:=SourceWorkbookDirectoryPath & SourceWorkbookName, _
FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=True
Kill SourceWorkbookDirectoryPath & "TargetWorkbook.xlsx"
End Sub
I hope it helps

Related

Excel into CSV VBA

I am having trouble saving one sheet from my workbook into a CSV file. I have 18 sheets in the one workbook. Every time I run the macro, it saves a different sheet. I also need it so the display alerts do not pop up. I am a beginner to VBA and running macros, so any help would be appreciated.
Sub csvfile()
'
' csvfile Macro
'
'
ChDir "C:\Users\RM\Documents"
ActiveWorkbook.SaveAs Filename:= _
"C:\Users\RM\Documents\Working_Program\PSSE_Export_Data.csv", FileFormat:= _
xlCSV, CreateBackup:=False
Application.DisplayAlerts = False
End Sub
This should do the trick, Just specify the sheet that you want to save in place of "Sheet1"
Sub csvfile()
Application.DisplayAlerts = False
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
ws.SaveAs Filename:= _
"C:\Users\RM\Documents\Working_Program\PSSE_Export_Data.csv", FileFormat:= _
xlCSV, CreateBackup:=False
End Sub

Macro to revert changes since save

I found an old script online to close the document without saving the changes, then re-open the document:
Sub RevertFile()
wkname = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
ActiveWorkbook.Close Savechanges:=False
Workbooks.Open Filename:=wkname
End Sub
I want this since you can't "undo" changes caused by running a macro. However, it does not seem to work in MS Office v1609. Firstly, the document does not re-open after it is closed. Secondly, the modifications are saved when I want them not to be. How can I rewrite this script to get it to work? Thanks.
[edit]
Here is the other sub-routine I am using.
Sub FixPlatforms()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim sht As Worksheet
Dim platList As Variant
Dim x As Long
platList = Array _
( _
"PS4", "PlayStation 4", _
"PS3", "PlayStation 3", _
"PS2", "PlayStation 2", _
"PSV", "PlayStation Vita", _
"PSP", "PlayStation Portable", _
"WIN", "Microsoft Windows", _
"SNES", "Super Nintendo Entertainment System" _
)
'Loop through each item in Array lists
For x = 1 To UBound(platList) Step 2
'Loop through each worksheet in ActiveWorkbook
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace What:=platList(x), Replacement:=platList(x - 1), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
Next x
End Sub
Is there something wrong with it?
You shouldn't have to close the workbook in any event. Attempting to open a workbook that is already open produces the following.
Adding application.displayalerts = false should be sufficient to avoid that confirmation.
Option Explicit
Sub RevertFile()
Dim wkname As String
wkname = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
Application.DisplayAlerts = False
Workbooks.Open Filename:=wkname
Application.DisplayAlerts = True
End Sub

Excel Macro to Copy & Paste Values from Multiple Sheets to Separate Text Files

I am trying to build a macro to export multiple sheets (with named tabs) to separate text files. The original .xlsm file has formulas built in, so I am trying to paste the values from each named worksheet into individual text files. The script below works, but only saves the main Excel file as .xlsx and the active worksheet.
I am trying to copy/paste all worksheets, but my script is not working:
Sub SaveSheetsAsTxt()
'
' SaveSheetsAsTxt Macro
'
Dim ws As Worksheet
Application.DisplayAlerts = False
'save as XLSX
ActiveWorkbook.SaveAs Filename:="V:\tech\dd\FUND_HOLDINGS.xlsx", _
FileFormat:=xlNormal, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
MyPath = ThisWorkbook.Path
For Each ws In ThisWorkbook.Sheets
ActiveSheet.Cells.Copy
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats
ActiveWorkbook.SaveAs Filename:="V:\tech\dd" & "\" & ActiveSheet.Name & ".txt", _
FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close SaveChanges:=False
Next ws
End Sub
Thank you in advance for any help!
There are a couple of things wrong with what you have there.
The Close statement doesn't need to be called inside the loop
The FileFormat for the .xlsx workbook needed to be changed to work properly when saving from .xlsm to .xlsx. it should be xlOpenXMLWorkbook
As Scott pointed out, you should activate the worksheet that you are trying to save each time as you iterate.
Sub SaveSheetsAsTxt()
Dim ws As Worksheet
Application.DisplayAlerts = False
'save as XLSX
Worksheets.Copy
ActiveWorkbook.SaveAs Filename:="V:\tech\dd\FUND_HOLDINGS.xlsx", _
FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
' Close the newly created xlsx file
ActiveWorkbook.Close
'loop through the worksheets
For Each ws In ThisWorkbook.Sheets
ws.Activate
ActiveSheet.Cells.Copy
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats
ActiveWorkbook.SaveAs Filename:="V:\tech\dd" & "\" & ActiveSheet.Name & ".txt", _
FileFormat:=xlText, CreateBackup:=False
Next ws
'Close out the workbook now
ActiveWorkbook.Close
End Sub

Save select sheets to HTML using VBA

I am using the following VBA to save specific sheets. I would like to save the sheets at HTML. I tried changing the . xls to .html but all I get is gobby gook (technical term) Any help would be appreciated.
Option Explicit
Sub TwoSheetsAndYourOut()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub
With Application
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, separated by commas
On Error GoTo ErrCatcher
Sheets(Array("Copy Me", "Copy Me2")).Copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Remove named ranges
For Each nm In ActiveWorkbook.Names
nm.Delete
Next nm
' Input box to name new file
NewName = InputBox("Please Specify the name of your new workbook", "New Copy")
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & NewName & ".xls"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
Use Ron de Bruin's RangetoHTML code. Call it from within your For Each ws... loop
I found the solution,
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & NewName & ".xls"
ActiveWorkbook.SaveAs Filename:="C:**locationtosave**.html", FileFormat:=xlHtml

How to copy only a single worksheet to another workbook using vba

I have 1 WorkBook("SOURCE") that contains around 20 Sheets.
I want to copy only 1 particular sheet to another Workbook("TARGET") using Excel VBA.
Please note that the "TARGET" Workbook doen't exist yet. It should be created at runtime.
Methods Used -
1) Activeworkbook.SaveAs <--- Doesn't work. This will copy all the sheets. I want only specific sheet.
I have 1 WorkBook("SOURCE") that contains around 20 Sheets. I want to copy only 1 particular sheet to another Workbook("TARGET") using Excel VBA. Please note that the "TARGET" Workbook doen't exist yet. It should be created at runtime.
Another Way
Sub Sample()
'~~> Change Sheet1 to the relevant sheet
'~~> This will create a new workbook with the relevant sheet
ThisWorkbook.Sheets("Sheet1").Copy
'~~> Save the new workbook
ActiveWorkbook.SaveAs "C:\Target.xlsx", FileFormat:=51
End Sub
This will automatically create a new workbook called Target.xlsx with the relevant sheet
To copy a sheet to a workbook called TARGET:
Sheets("xyz").Copy After:=Workbooks("TARGET.xlsx").Sheets("abc")
This will put the copied sheet xyz in the TARGET workbook after the sheet abc
Obviously if you want to put the sheet in the TARGET workbook before a sheet, replace Before for After in the code.
To create a workbook called TARGET you would first need to add a new workbook and then save it to define the filename:
Application.Workbooks.Add (xlWBATWorksheet)
ActiveWorkbook.SaveAs ("TARGET")
However this may not be ideal for you as it will save the workbook in a default location e.g. My Documents.
Hopefully this will give you something to go on though.
You can try this VBA program
Option Explicit
Sub CopyWorksheetsFomTemplate()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub
With Application
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
Sheets(Array("Sheet1", "Sheet2")).Copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Remove named ranges
For Each nm In ActiveWorkbook.Names
nm.Delete
Next nm
' Input box to name new file
NewName = InputBox("Please Specify the name of your new workbook", "New Copy")
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & NewName & ".xls"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
The much longer example below combines some of the useful snippets above:
You can specify any number of sheets you want to copy across
You can copy entire sheets, i.e. like dragging the tab across, or you can copy over the contents of cells as values-only but preserving formatting.
It could still do with a lot of work to make it better (better error-handling, general cleaning up), but it hopefully provides a good start.
Note that not all formatting is carried across because the new sheet uses its own theme's fonts and colours. I can't work out how to copy those across when pasting as values only.
Option Explicit
Sub copyDataToNewFile()
Application.ScreenUpdating = False
' Allow different ways of copying data:
' sheet = copy the entire sheet
' valuesWithFormatting = create a new sheet with the same name as the
' original, copy values from the cells only, then
' apply original formatting. Formatting is only as
' good as the Paste Special > Formats command - theme
' colours and fonts are not preserved.
Dim copyMethod As String
copyMethod = "valuesWithFormatting"
Dim newFilename As String ' Name (+optionally path) of new file
Dim themeTempFilePath As String ' To temporarily save the source file's theme
Dim sourceWorkbook As Workbook ' This file
Set sourceWorkbook = ThisWorkbook
Dim newWorkbook As Workbook ' New file
Dim sht As Worksheet ' To iterate through sheets later on.
Dim sheetFriendlyName As String ' To store friendly sheet name
Dim sheetCount As Long ' To avoid having to count multiple times
' Sheets to copy over, using internal code names as more reliable.
Dim colSheetObjectsToCopy As New Collection
colSheetObjectsToCopy.Add Sheet1
colSheetObjectsToCopy.Add Sheet2
' Get filename of new file from user.
Do
newFilename = InputBox("Please Specify the name of your new workbook." & vbCr & vbCr & "Either enter a full path or just a filename, in which case the file will be saved in the same location (" & sourceWorkbook.Path & "). Don't use the name of a workbook that is already open, otherwise this script will break.", "New Copy")
If newFilename = "" Then MsgBox "You must enter something.", vbExclamation, "Filename needed"
Loop Until newFilename > ""
' If they didn't supply a path, assume same location as the source workbook.
' Not perfect - simply assumes a path has been supplied if a path separator
' exists somewhere. Could still be a badly-formed path. And, no check is done
' to see if the path actually exists.
If InStr(1, newFilename, Application.PathSeparator, vbTextCompare) = 0 Then
newFilename = sourceWorkbook.Path & Application.PathSeparator & newFilename
End If
' Create a new workbook and save as the user requested.
' NB This fails if the filename is the same as a workbook that's
' already open - it should check for this.
Set newWorkbook = Application.Workbooks.Add(xlWBATWorksheet)
newWorkbook.SaveAs Filename:=newFilename, _
FileFormat:=xlWorkbookDefault
' Theme fonts and colours don't get copied over with most paste-special operations.
' This saves the theme of the source workbook and then loads it into the new workbook.
' BUG: Doesn't work!
'themeTempFilePath = Environ("temp") & Application.PathSeparator & sourceWorkbook.Name & " - Theme.xml"
'sourceWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
'sourceWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
'newWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
'newWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
'On Error Resume Next
'Kill themeTempFilePath ' kill = delete in VBA-speak
'On Error GoTo 0
' getWorksheetNameFromObject returns null if the worksheet object doens't
' exist
For Each sht In colSheetObjectsToCopy
sheetFriendlyName = getWorksheetNameFromObject(sourceWorkbook, sht)
Application.StatusBar = "VBL Copying " & sheetFriendlyName
If Not IsNull(sheetFriendlyName) Then
Select Case copyMethod
Case "sheet"
sourceWorkbook.Sheets(sheetFriendlyName).Copy _
After:=newWorkbook.Sheets(newWorkbook.Sheets.count)
Case "valuesWithFormatting"
newWorkbook.Sheets.Add After:=newWorkbook.Sheets(newWorkbook.Sheets.count), _
Type:=sourceWorkbook.Sheets(sheetFriendlyName).Type
sheetCount = newWorkbook.Sheets.count
newWorkbook.Sheets(sheetCount).Name = sheetFriendlyName
' Copy all cells in current source sheet to the clipboard. Could copy straight
' to the new workbook by specifying the Destination parameter but in this case
' we want to do a paste special as values only and the Copy method doens't allow that.
sourceWorkbook.Sheets(sheetFriendlyName).Cells.Copy ' Destination:=newWorkbook.Sheets(newWorkbook.Sheets.Count).[A1]
newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlValues
newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlFormats
newWorkbook.Sheets(sheetCount).Tab.Color = sourceWorkbook.Sheets(sheetFriendlyName).Tab.Color
Application.CutCopyMode = False
End Select
End If
Next sht
Application.StatusBar = False
Application.ScreenUpdating = True
ActiveWorkbook.Save
Sub ActiveSheet_toDESKTOP_As_Workbook()
Dim Oldname As String
Dim MyRange As Range
Dim MyWS As String
MyWS = ActiveCell.Parent.Name
Application.DisplayAlerts = False 'hide confirmation from user
Application.ScreenUpdating = False
Oldname = ActiveSheet.Name
'Sheets.Add(Before:=Sheets(1)).Name = "FirstSheet"
'Get path for desktop of user PC
Path = Environ("USERPROFILE") & "\Desktop"
ActiveSheet.Cells.Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "TransferSheet"
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveSheet.Cells.Copy
'Create new workbook and past copied data in new workbook & save to desktop
Workbooks.Add (xlWBATWorksheet)
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveSheet.Cells(1, 1).Select
ActiveWorkbook.ActiveSheet.Name = Oldname '"report"
ActiveWorkbook.SaveAs Filename:=Path & "\" & Oldname & " WS " & Format(CStr(Now()), "dd-mmm (hh.mm.ss AM/PM)") & ".xlsx"
ActiveWorkbook.Close SaveChanges:=True
Sheets("TransferSheet").Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Worksheets(MyWS).Activate
'MsgBox "Exported to Desktop"
End Sub