Repeat a sub command - vba

I want to move sheets to a new workbook and save it as a new workbook with the sheet name. I have got that part, but I want to repeat it until all the sheets are moved from the main workbook.
the code I used is below:
Sub MoveToNew()
'Move the active sheet to a new Workbook.
Activesheet.Move
MName = Activesheet.Name & ".xls"
MDir = ActiveWorkbook.Path
ActiveWorkbook.SaveAs Filename:="C:\Users\DICS-IN\Desktop\Check\" & MName
ActiveWorkbook.Save
ActiveWorkbook.Close
It works until this but I want the same thing to be repeated until all the sheets are moved and saved separately from the main sheet.
I found Dim as Integer and etc but couldn't do it.

loop through all sheets using a For Each ... Next loop
Example:
Sub test()
Dim S As Worksheet
' loop through all worksheets
For Each S In ActiveWorkbook.Worksheets
Debug.Print S.Name
' do something with S
Next S
End Sub

Related

Excel VBA execute code in newly created workbook

I'm trying to save one worksheet in my excel file to a new file, but without the formula's.
I have this code that is working to get the file saved:
Sub SaveInvoice()
'Create a filename based on invoicenumber
Dim FileName As String
FileName = Sheets("Sale").Range("C3").Value
'Copy the "Print" sheet
Worksheets("Print").Copy
With ActiveWorkbook
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
End Sub
This works like a charm, however I need to strip out the formula's so I googled and fount this piece of code:
ActiveSheet.Copy
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
And this works as well, however once I merge the two pieces of code together the whole function breaks.
With ActiveWorkbook
'Transform cells to values
ActiveSheet.Copy
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
This results in my base worksheet beeing stripped from formula's.
I need to know how I can call the function on the newle created workbook.
When copying a worksheet with no Destination excel creates a New Workbook, and the New Workbook with its only Worksheet are active.
EDIT: I just realized that in the final code these lines from the original code:
'Copy the "Print" sheet
Worksheets("Print").Copy
Were moved inside the
With ActiveWorkbook
That was previously referring to the New Workbook created by the Worksheet.Copy and that now refers to the Source Workbook
So let see what the Op's final code is actually doing:
Here the ActiveWorkbook is the [Source Workbook] and the ActiveSheet must be [Print]
With ActiveWorkbook
This copies the ActiveSheet creating a New Workbook with only one sheet
ActiveSheet.Copy
These lines are affecting the ActiveSheet [Print] in the [Source Workbook].
Not because of the With statement but because it's the one active
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
The commands within a With intended to affect object that it refers to must start with a dot [.]; however these lines are invalid because Cells and Range are not Methods nor Properties of the Workbook Object, thus en error would have been triggered.
With Statement
Executes a series of statements on a single object or a user-defined type.
(from the msdn.microsoft.com help)
This saves the Workbook referred by the With statement, which still has the formulas
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
Try this code:
Sub SaveInvoice_TEST_1()
'Create a filename based on invoicenumber
Dim FileName As String
With ThisWorkbook
FileName = .Sheets("Sale").Range("C3").Value
'Copy the "Print" sheet
.Worksheets("Print").Copy
End With
With ActiveWorkbook
Rem Replace Formulas with Values
.Sheets(1).UsedRange.Value = .Sheets(1).UsedRange.Value2
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
End Sub
Suggest to read the following pages to gain a deeper understanding of the resources used:
With Statement
Try something like the following. Read the help page for 'ActiveSheet.Copy' - note that it creates a new workbook and activates it
Dim MyWkbk as workbook
set MyWkbk = ActiveWorkbook
ActiveSheet.Copy
With ActiveWorkbook
Cells.Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
'Save the file as new
.SaveAs FileName:="C:\" & FileName
'.close
End With
MyWkBk.activate
Thanks to #EEM the solution was found.
Here's the code I used:
Sub SaveInvoice()
Dim FileName As String
With ThisWorkbook
'Create a filename based on invoicenumber
FileName = .Sheets("Sale").Range("C3").Value
'Copy the "Print" sheet
.Worksheets("Print").Copy
End With
With ActiveWorkbook
'Replace Formulas with Values
.Sheets(1).UsedRange.Value = .Sheets(1).UsedRange.Value2
'Save the file as new
.SaveAs FileName:="C:\" & FileName
End With
End Sub

Can I copy a sheet to a new workbook if it's hidden

So maybe I'm just not getting something here, but I have a hidden worksheet that list several columns based on other hidden sheets. I'm trying to minimize user intervention... :-)
I want to copy Hidden sheet 1 into a brand new workbook as an available sheet with the aforementioned values. Code that works when hiddensheet is visible:
Dim wbNew As Workbook
Application.DisplayAlerts = False
Worksheets("HiddenSheet").Copy
Set wbNew = ActiveWorkbook
With wbNew
With .Worksheets(1).UsedRange
.Value = .Value
End With
.SaveAs ThisWorkbook.Path & "\"
.Close True
End With
So I'd like to still copy the sheet to a new workbook....just want to do it with the sheet hidden.
Any thoughts?
Absolutely place this line:
Worksheets("HiddenSheet").Visible = xlSheetVisible
before this line:
Worksheets("HiddenSheet").copy
is is impossible to copy a hidden sheet to a new workbook
the new workbook would only have 1 sheet (hidden), but every wb needs at least one visible sheet
if you create a visible sheet and copy your hidden sheed later into it, it works
Sub Makro1()
Dim wbNew As Workbook
Set wbNew = Workbooks.Add
ThisWorkbook.Sheets("Hidden Sheet").Copy Before:=wbNew.Sheets(1)
End Sub
try it :)

Why does Excel VBA generate the error "Copy method of Sheets class failed" on some sheets, but not others?

I am trying to come up with code that will make copies of all the worksheets in a given workbook. Seems simple enough, right? A little Google searching and I cobbled together the following code:
Sub Commandbutton1_click()
Dim Cnt As Long
Dim i As Long
Dim Sht1 As String
Dim MyChoice As String
Dim MyFile As String
Dim CurrWorkBook As Excel.Workbook
Dim Month As String
'Instructional message box
MsgBox "When the 'Open' dialog appears, select the workbook containing the worksheets you want to split and then click Ok."
'Get file name
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Show
MyChoice = .SelectedItems(1)
End With
Application.ScreenUpdating = False
MyFile = Dir(MyChoice)
Set CurrWorkBook = Workbooks.Open(Filename:=MyFile)
CurrWorkBook.Activate
Cnt = Sheets.Count
InputMsg = "Enter the month of the EOM Budget Review:"
InputTitle = "Month"
Month = InputBox(InputMsg, InputTitle)
For i = 1 To Cnt Step 1
Sht1 = Sheets(i).Name
Sheets(Array(Sht1)).Copy
ActiveWorkbook.SaveAs Filename:=Sht1 & " - " & Month & " EOM Budget Review.xlsx", _
FileFormat:=51, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
ActiveWorkbook.Close
Next i
CurrWorkBook.Save
CurrWorkBook.Close
Application.ScreenUpdating = True
End Sub
It works perfectly...except when it doesn't. In some workbooks, it will copy every sheet with no difficulty. In some workbooks, it will copy some of the sheets, but throw the "Copy method of Sheets class failed" unless you have it skip certain sheets. I have not been able to figure out what the sheets it will not copy have in common. Is there some way I can improve this code? Are there certain features of worksheets that will cause this kind of code to fail inevitably?
Solved thanks to Alex P.'s comment above. I copied the following code from another forum:
Sub UnhideAll()
Dim WS As Worksheet
For Each WS In Worksheets
WS.Visible = True
Next
End Sub
Then I used Call UnhideAll right after Application.ScreenUpdating = False. I also used CurrWorkBook.Close savechanges:=False at the end so that the workbook being copied would not be saved and its hidden worksheets would go back to being hidden.

VBA: Auto save&close out of all current workbooks except for Macro workbook

I'm trying to close all currently open Workbooks except for my Macro workbook, and .SaveAs my path, but I want my path to be a specified cell within my macro workbook [D1] to be precise. I also want the file name to be saved as cell A1 in the Workbook that I'm currently saving and closing out of. Now I'm stuck. I've listed the code that I'm utilizing currently, and the issue I'm running into with this piece of code is that it's saving as the name in cell A1 in the currently selected Workbook vs the Workbook the code is currently cycling on. I hope this makes sense.
Option Explicit
Public ThisFile As String
Public Path As String
Sub CloseAndSaveOpenWorkbooks()
Dim Wkb As Workbook
' ThisFile = ActiveWorkbook.Sheets(1).Range("A1").Value ** Commented out as this piece of code was not working as intended **
Path = "C:\Users\uuis\Desktop"
With Application
.ScreenUpdating = False
' Loop through the workbooks collection
For Each Wkb In Workbooks
With Wkb
If .Name <> ThisWorkbook.Name Then
' if the book is read-only
' don't save but close
If Not Wkb.ReadOnly Then
.SaveAs Filename:=(Path & "\" & ActiveWorkbook.Sheets(1).Range("A1").Value & ".xls"), FileFormat:=xlExcel8
End If
' We save this workbook, but we don't close it
' because we will quit Excel at the end,
' Closing here leaves the app running, but no books
.Close
End If
End With
Next Wkb
.ScreenUpdating = True
' .Quit 'Quit Excel
End With
End Sub
ActiveWorkbook.Sheets(1).Range("A1").Value
should be
Wkb.Sheets(1).Range("A1").Value

Access another workbook from current workbook which contains the macro

I have a code written for one excel sheet in the form of Macro, In this macro, I am generating a copy of current workbook to a different location. Now, I need to access this copied excel workbook to delete some of its Worksheets from the macro.
can anyone tell me how to access the newly copied sheet from the current excel sheet macro?
The following code will allow you to edit a copy of your workbook:
Sub test()
Dim wb As Workbook
Dim strName as String
strName = "" & ActiveWorkbook.Name
ActiveWorkbook.SaveCopyAs Filename:=strName
Set wb = Workbooks.Open(strName)
Application.DisplayAlerts = False 'Prevents that user is asked when sheets are deleted
wb.Worksheets("Sheet1").Delete
Application.DisplayAlerts = True
wb.Close SaveChanges:=True
End Sub