Save Selected Sheets to a different work book in VBA - vba

I would like to save a number of worksheets from the current workbook to a different workbook and exclude a sheet named "buttons" (in current one) from that saving process.
Can anybody help please? The number of worksheets is changeable FYI.
Below is what I have so far which include all the sheets from current workbook.
Sub SaveAs()
D1 = VBA.Format(Now, "mm_DD_yyyy")
For Each ws In Application.Workbooks
ws.SaveAs Filename:="C:\Users\e2309\Desktop\Andy's\GBB_Report_" & D1 & ".csv"
Next ws
Application.Quit
End Sub

Or more directly
copy the entire workbook
delete the redundant sheet
code
Sub Simpler()
Dim wb As Workbook
Dim strFile As String
strFile = "C:\temp\yourfile.xlsm"
ThisWorkbook.SaveAs strFile, xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = False
ThisWorkbook.Sheets("buttons").Delete
Application.DisplayAlerts = True
End Sub

This might get you a little closer. Note this is not complete and very untested.
Sub work()
Dim WB As Workbook
Dim Nwb As Workbook
Dim WS As Worksheet
Set Nwb = New Workbook
Set WB = ThisWorkbook
For Each WS In WB.Sheets
If WS.Name <> "Don't copy" Then
WS.Copy Nwb.Sheets("sheet1")
End If
Next
Nwb.Save
End Sub

Related

Vba macro subscript out of range

Can't seem to figure out why I'm getting a run time error on the second line. Help please
Dim wb As Workbook
Set wb = Workbooks(PLC)
wb.Close SaveChanges:False
Application.DisplayAlerts=True
End sub
give this a shot
Sub test()
Dim wb As Workbook
Set wb = Workbooks("PLC.xlsx")
wb.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
When you wish to open a workbook you should use the Workbooks.Open method. Workbooks(index) only applies to workbooks that are already opened. You can check if a workbook is already open by doing e.g.
Dim wb as workbook, isOpen as boolean, myName as string
myName = "PLC"
bIsOpen = false
For each wb in Workbooks
If wb.Name = myName Then
bIsOpen = true
End if
Next wb
And use the result in your next step.

Excel VBA - Copying all Worksheets from a specific workbook into an active workbok

I'm trying to copy all worksheets from a file saved on a network drive into my current active workbook. After they are copied I would like to hide them.
The tricky part, which I have yet to been able to find, is every time the macro is re-run I would like those worksheets that were previously copied over to be overwritten or deleted and replaced by the new worksheets from the existing file I am copying from.
Currently, I have my code set up to just copy over a specific worksheet depending on the string of a hyperlink. Below is what I've started but its not quite the direction I want to head.
Note the below is the edited script:
Sub ImportWorksheets()
Dim wb As Workbook, ws As Worksheet, wbTarget As Workbook, wsTarget As Worksheet
Application.ScreenUpdating = False
Dim pth As String
pth = wb.Path
Dim titleDetailPth As String
titleDetailPth = Left(pth, InStrRev(pth, "\") - 1)
Dim filePthName As String
filePthName = titleDetailPth & "\New Release Templates\" & "Key New Release Accounts Details.xlsx"
Set wb = ActiveWorkbook 'Your workbook
Set wbTarget = Workbooks.Open(filePthName, UpdateLinks:=False, ReadOnly:=True) 'The drive workbook
For Each wsTarget In wbTarget.Worksheets 'a loop for each worksheet on the drive workbook
For Each ws In wb.Worksheets ' a loop for each worksheet on your workbook
If wsTarget.Name = ws.Name Then 'if the sheet you are trying to import exist, it will delete it
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wsTarget.Copy After:=wb.Sheets(wb.Sheets.Count) 'this will copy it into the last sheet
wb.Sheets(wb.Sheets.Count).Visible = 0 'this will hide it
Next wsTarget
wbTarget.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub
Then this should do the work for you:
Sub ImportWorksheets()
Dim wb As Workbook, ws As Worksheet, wbTarget As Workbook, wsTarget As Worksheet
Application.ScreenUpdating = False
Set wb = ThisWorkbook 'Your workbook
Set wbTarget = Workbooks.Open("wherever your drive file is", UpdateLinks:=False, ReadOnly:=True) 'The drive workbook
For Each wsTarget In wbTarget.Worksheets 'a loop for each worksheet on the drive workbook
For Each ws In wb.Worksheets ' a loop for each worksheet on your workbook
If wsTarget.Name = ws.Name Then 'if the sheet you are trying to import exist, it will delete it
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wsTarget.Copy After:=wb.Sheets(wb.Sheets.Count) 'this will copy it into the last sheet
wb.Sheets(wb.Sheets.Count).Visible = 0 'this will hide it
Next wsTarget
wbTarget.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub

How do I ensure the VBA code saves the workbook to the file path declared?

The following is my code in an attempt to delete a number of sheets in order to save a workbook with specific worksheets only:
Sub SeperateWB2()
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
ddl = "PhaseTransferDropDowns"
sheetname = InputBox("Please specify sheet name:")
Path = "C:\My Documents\Phase Transfer\Test\"
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If Not ws.Name = sheetname And Not ws.Name = ddl Then
Application.DisplayAlerts = False
ws.Delete
End If
Next ws
wb.SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
wb.Close
Set wb = Nothing
End Sub
The loop works fine but it refuses to save the workbook on the path I have specified.
I get this message: "Runtime error 91: Object variable or With block variable not set"
Can anyone help?
Look at your error message: Object variable or With block variable not set
It looks like you aren't able to save because you never instantiate your wb variable. Therefore wb = Nothing. You can't perform SaveAs on nothing. Try adding Set wb = ThisWorkbook below your declarations like so:
'other code
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
'other code
The wb object variable is never assigned to anything other than Nothing. But anyway you can use ThisWorkook, if you mean to save and close the workbook that contains the running code:
With ThisWorkbook
.SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
.Close
End With
Thanks everyone!
It seems that I needed to set the workbook properly (Set wb = ThisWorkbook).
I also needed to change ws.name into sheetname.
This is the code that worked at the end:
Sub SeperateWB2()
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
sheetname = InputBox("Please specify sheet name:")
Path = "C:\My Documents\Phase Transfer\Test\"
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If Not ws.Name = sheetname And Not ws.Name = ddl Then
Application.DisplayAlerts = False
ws.Delete
End If
Next ws
wb.SaveAs Path & sheetname & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
'wb.Close
End Sub

VBA delete all worksheets in all workbooks that dont equal "summary details"

I cant seem to get the code to loop to the next workbook open. After that I would like to consolidate all the single worksheets in each workbook into a single workbook and rename each tab based on it's workbook name.
I am not too far but sentence one is my first task
Sub cullworkbooksandCONSOLIDATE()
Dim ws As Worksheet
Dim wb As Workbook
Dim wsNAME As String
For Each wb In Application.Workbooks
With wb
For Each ws In ActiveWorkbook.Worksheets
With ws
wsNAME = ws.Name
If wsNAME <> "summary details" Then
ws.Delete
End If
End With
Next
End With
Next
End Sub
thank you kindly
Or more directly, just copy the sheet if it exists, rather than deleting all the non matches (which will also cause an error if the code deletes all sheets)
Sub cullworkbooksandCONSOLIDATE()
Dim wb As Workbook
Dim wb1 As Workbook
Dim ws As Worksheet
Dim wsNAME As String
Set wb1 = Workbooks.Add(1)
wsNAME = "summary details"
For Each wb In Application.Workbooks
With wb
If .Name <> wb1.Name Then 'if it's not the export workbook
On Error Resume Next
Set ws = wb.Sheets(wsNAME)
On Error GoTo 0
If Not ws Is Nothing Then ws.Copy Before:=wb1.Sheets(1)
End If
End With
Next
End Sub
This is so not going into my resumé.
Sub cullworkbooksandCONSOLIDATE()
Dim ws As Worksheet
Dim wb As Workbook
Dim wsNAME As String
Dim wbex As Workbook
'You'll need to define wbex, this is where your worksheets will be inserted
For Each wb In Application.Workbooks
With wb
If .Name <> wbex.Name Then 'if it's not the export workbook
For Each ws In wb.Worksheets 'not necessarily active workbook
With ws
wsNAME = LCase(.Name)
If wsNAME <> "summary details" Then
.Delete 'why do you need to delete it?
Else
.Name = wb.Name
.Copy Before:=wbex.Sheets(1)
End If
End With
Next
.Close SaveChanges:=False 'you really don't want to corrupt your source data, do you?
End If
End With
Next
End Sub

VBA Copy/Paste from one Sheet to All Others

I am trying to copy one cell (D1) of sheet1 to a cell (D1) of all the workbook's other sheets (I am looping through files here and the number of worksheet varies).
When running the code below, the line "ActiveSheet.Paste" gives me the following error: "Run-time error '10004': Paste method of Worksheet class failed".
Here is the problematic piece of code:
'copy MSA code to sheets!=1
Sub MSAallSheets(wb As Workbook)
With wb
Range("D1").Copy
For Each ws In wb.Worksheets
If ws.Name <> "Page 1" Then
ws.Activate
ws.Range("D1").Select
ActiveSheet.Paste
End If
Next
End With
End Sub
In case it might be necessary, here is how I defined my loop through files:
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = "C:\Users\julia.anderson\Documents\HMDA\test\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
Delete wb
MSAallSheets wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
Suggestions would be most welcome!
Thank you.
I'm guessing which sheet you're copying from...
Sub MSAallSheets(wb As Workbook)
With wb
Range("D1").Copy
For Each ws In wb.Worksheets
If ws.Name <> "Page 1" Then
wb.Sheets("Page 1").Range("D1").Copy _
ws.Range("D1")
End If
Next
End With
End Sub
This works for me with a slight alteration:
Sub MSAallSheets(wb As Workbook, SourceSheet As String, SourceAddress As String)
With wb
Sheets(SourceSheet).Range(SourceAddress).Copy
For Each ws In wb.Worksheets
If ws.Name <> SourceSheet Then
ws.Activate
ws.Range(SourceAddress).Select
ActiveSheet.Paste
End If
Next
End With
End Sub
example call:
call MSAallSheets(activeWorkbook, "Page 1", "D1")
The parameters make it easier to change minor details / reuse the code.