VBA Copy/Paste from one Sheet to All Others - vba

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.

Related

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 to Open Excel File and Paste Sheet 1 Data into “Main” Sheet in Current Workbook

Ok so I have a current workbook (Original Workbook) with one Sheet.
I would like to open an existing workbook (Data Workbook) and copy all of the contents in Sheet 1 of 'Data Workbook', then paste everything into Sheet "Main" of 'Original Workbook'.
At the end of this process I would like to close the 'Data Workbook' So far I have the following code.
however it gives me an error message
"Run-time error'1004': Cannot paste that macro formula onto a worksheet":
Sub ImportData()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range
Set wb1 = ActiveWorkbook
Set PasteStart = [Main!A1]
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
With Sheet.UsedRange
.Copy PasteStart
Set PasteStart = PasteStart.Offset(.Rows.Count)
End With
Next Sheet
End If
wb2.Close
End Sub
Hello please refer the code below and make changes according to your need. It does what you need.
Option Explicit
Sub import()
Dim filename As String
Dim curfilename As String
curfilename = ThisWorkbook.Name
filename = Application.GetOpenFilename
Application.ScreenUpdating = False
Dim x As Workbook
Set x = Workbooks.Open(filename)
With Sheets("1")
x.Sheets("1").Range("A1:Z10000").Copy '/Provide the range
End With
Dim y As Workbook
Set y = Workbooks(curfilename)
With Sheets("Main")
y.Sheets("Main").Range("A1").PasteSpecial xlPasteFormats
Application.DisplayAlerts = False
End With
x.Close SaveChanges:=False
Range("A1").Select
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

Save Selected Sheets to a different work book in 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

Excel VBA: Copying multiple sheets into new workbook

I have an error message of 'Object Required' when I run this sub. I have a version for copying each specific sheet, which works fine, but this sub is for all sheets within the WB ie to copy each one's WholePrintArea and paste it into a new sheet in the new WB. Thanks...
Sub NewWBandPasteSpecialALLSheets()
MyBook = ActiveWorkbook.Name ' Get name of this book
Workbooks.Add ' Open a new workbook
NewBook = ActiveWorkbook.Name ' Save name of new book
Workbooks(MyBook).Activate ' Back to original book
Dim SH As Worksheet
For Each SH In MyBook.Worksheets
SH.Range("WholePrintArea").Copy
Workbooks(NewBook).Activate
With SH.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):
Sub NewWBandPasteSpecialALLSheets()
MyBook = ActiveWorkbook.Name ' Get name of this book
Workbooks.Add ' Open a new workbook
NewBook = ActiveWorkbook.Name ' Save name of new book
Workbooks(MyBook).Activate ' Back to original book
Set WB = ActiveWorkbook
Dim SH As Worksheet
For Each SH In WB.Worksheets
SH.Range("WholePrintArea").Copy
Workbooks(NewBook).Activate
With SH.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:
Sub NewWBandPasteSpecialALLSheets()
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Set wb = ThisWorkbook
Workbooks.Add ' Open a new workbook
Set wbNew = ActiveWorkbook
On Error Resume Next
For Each sh In wb.Worksheets
sh.Range("WholePrintArea").Copy
'add new sheet into new workbook with the same name
With wbNew.Worksheets
Set shNew = Nothing
Set shNew = .Item(sh.Name)
If shNew Is Nothing Then
.Add After:=.Item(.Count)
.Item(.Count).Name = sh.Name
Set shNew = .Item(.Count)
End If
End With
With shNew.Range("A1")
.PasteSpecial (xlPasteColumnWidths)
.PasteSpecial (xlFormats)
.PasteSpecial (xlValues)
End With
Next
End Sub
Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.
This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)
Sub Create_new_file()
Application.DisplayAlerts = False
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String
Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook
For Each sh In wb.Worksheets
pname = sh.Name
If sh.Visible = True Then
sh.Copy After:=wbNew.Sheets(Sheets.Count)
wbNew.Sheets(Sheets.Count).Cells.ClearContents
wbNew.Sheets(Sheets.Count).Cells.ClearFormats
wb.Sheets(sh.Name).Activate
Range(sh.PageSetup.PrintArea).Select
Selection.Copy
wbNew.Sheets(pname).Activate
Range("A1").Select
With Selection
.PasteSpecial (xlValues)
.PasteSpecial (xlFormats)
.PasteSpecial (xlPasteColumnWidths)
End With
ActiveSheet.Name = pname
End If
Next
wbNew.Sheets("Hoja1").Delete
Application.DisplayAlerts = True
End Sub
Since you are copying all worksheet, how about:
Copy & Paste (X)
SaveAS (O)
Sub Export()
Application.DisplayAlerts = False
On Error Resume Next
Dim NewWB As String
NewWB = Sheets("Control").Range("B42")
ActiveWorkbook.SaveAs Filename:=NewWB, FileFormat:=xlWorkbookNormal
ActiveWorkbook.Sheets("Control").Delete
End Sub
I had a worksheet "Control" handling all variant, you may change it yourself
On the other hand, if you really wish to use COPY & PASTE, you could use ARRAY
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=FolderPath & ExcelName & ".xlsx", FileFormat:=xlNormal
Workbooks(ExcelOrigin).Activate
Sheets(Array("for coversheet", "Pivot", "CCA", "FRR", "CRS", "GSA", "Inv Summary", "UploadtoJDE", "Comat")).Copy Before:=Workbooks(ExcelName).Sheets(1)
Sheets("Sheet1").Delete
Remember to Dim (FolderPath,ExcelName,ExcelOrigin) as String
As equal them to your file name & file path
[ i can't type in those here because of error ]