I am trying to copy 4 sheets from 4 different workbooks into the 'Master' workbook that I am in
The below code just does it for one sheet but I want to do it for all 4 sheets
Also, currently the code below opens up the source sheet but I don't want to open source sheets. If I remove '.Open" from below file path then it says subscript out of range
Thanks
Sub Copysheets()
Dim source As Workbook
Dim Master As Workbook
Set source = Workbooks.Open("\\filepath\filename.xlsx")
Set Master = Workbooks.Open("\\filepath\filename.xlsm")
Dim sourcesheet As Worksheet
For Each sourcesheet In source.Sheets
sourcesheet.Copy After:=Master.Sheets(Master.Sheets.Count)
Next
End Sub
If you have a task that you need to do repeated times, usually it's a good idea outsource the task to a subroutine.
The following routine gets 2 parameters, the first is the master (the workbook where you want to copy the sheets into) and a filename (with the name of the file to be opened and copied). This copy-routine doesn't care about your business logic, it simply copies the sheets:
Sub Copysheets(masterWB As Workbook, sourceWBName As String)
Dim sourceWB As Workbook, sourceSheet As Worksheet
Set sourceWB = Workbooks.Open(sourceWBName)
For Each sourceSheet In sourceWB.Sheets
sourceSheet.Copy After:=masterWB.Sheets(masterWB.Sheets.Count)
Next
' Don't forget to close the file afterwards:
sourceWB.Close SaveChanges:=False
End Sub
You could then call the the routine like this (this piece of code handles your business logic but doesn't care about how the copy is done):
Sub CopySheetsFrom4Workbooks()
Dim masterWB As Workbook
Set masterWB = Workbooks.Open("\\filepath\filename.xlsm")
Copysheets masterWB, "\\filepath\filename1.xlst"
Copysheets masterWB, "\\filepath\filename2.xlst"
Copysheets masterWB, "\\filepath\filename3.xlst"
Copysheets masterWB, "\\filepath\filename4.xlst"
masterWB.Save
End Sub
or, for example, use a loop to copy sheets of all files:
Sub CopyAllMyWorkbooks()
Dim masterWB As Workbook
Set masterWB = Workbooks.Open("\\filepath\filename.xlsm")
Dim sourceFilename As String
sourceFilename = Dir("\\filepath\filename*.xlst")
Do While sourceFilename <> ""
Copysheets masterWB, sourceFilename
sourceFilename = Dir
Loop
End Sub
Related
I have a workbook with many sheets. I'm trying to copy two sheets together to a new workbook.
I get
Run-time error 13 for type mismatch.
Sub CopyBillStatandCosts()
Dim MyBook As Workbook
Dim NewBook As Workbook
Set MyBook = ThisWorkbook
Workbooks.Add ' Open a new workbook
Set NewBook = ActiveWorkbook
Set MyBook = ActiveWorkbook
Sheets(11).Copy Before:=Workbooks(NewBook).Sheets(1)
Sheets(9).Copy Before:=Workbooks(NewBook).Sheets(1)
Workbooks(NewBook).Sheet1.Delete
End Sub
Update: I figured out the code. But how do I refer to the sheets by their code names, which is best practice? They are sheet9 and sheet 11.
Sub copyBillStatandCosts()
ThisWorkbook.Worksheets(Array("BillStat", "C")).Copy
End Sub
Your second
Set MyBook = ActiveWorkbook
was probably meant to be
MyBook.Activate
although an overall simpler way to do this would be
Sub CopyBillStatandCosts()
Sheets(Array("BillStat", "Costs")).Copy
End Sub
The Copy with no parameter makes the copy in a new workbook.
Copy Worksheets by Code Name in One Go
Sub copyBillStatandCosts()
ThisWorkbook.Worksheets(Array(Sheet9.Name, Sheet11.Name)).Copy
' To continue to work with the new workbook, do the following:
Dim NewBook As Workbook: Set NewBook = ActiveWorkbook
' e.g.:
' NewBook.SaveAs "C:\Test\Test.xlsx", xlOpenXMLWorkbook
' To continue to work with each new worksheet, do the following:
Dim bws As Worksheet: Set bws = NewBook.Worksheets(1)
Dim cws As Worksheet: Set cws = NewBook.Worksheets(2)
' e.g.:
MsgBox NewBook.Name & vbLf & bws.Name & vbLf & cws.Name
End Sub
Why use code names? Now you can rename the two worksheets in the tabs, and the code will still copy the right ones to a new workbook.
Why in one go? If there are references of the worksheets from one to each other they will still work in the new workbook i.e. will not refer to the worksheets in the source workbook.
If you wanna use programmatic names, then just use Name property:
ThisWorkbook.Sheets(Array(sheet9.Name, sheet11.Name)).Copy
I am currently working on a VBA script to automate a excel sheet. The goal is to have the code open a file from using a file path in cell A2 on a sheet called Reports (the file path is dynamic and is formed using information from the sheet) , copy the data from the file for range A1:E200 and to paste the data into the original workbook on a sheet called HOURS starting at A1. At the moment i have gotten to the point where the file is opened but there is a "Mismatch" error when trying to copy the information across. Below I've attached the code used. I was hoping that someone would be able to help to make sense of the error! I am having the same problem with the close section as well. Note: I am a rookie on VBA so if you could be as clear as possible
Sub Button1_Click()
Call Test
Call Copy_Method
Call CloseWorkbook
End Sub
Sub Test()
Dim strFName As String
strFName = Sheet4.Range("A2").Value
Workbooks.Open Filename:=strFName
End Sub
Sub Copy_Method()
'Copy range to another workbook using Range.Copy Method
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb2 = ThisWorkbook
Set ws2 = wb2.Sheets("HOURS")
Set wb1 = ThisWorkbook.Worksheets("Reports").Range("A2")
Set ws1 = wb1.Sheets("Sheet")
ws2.Range("A1:E200") = ws1.Range("A1:E200").Value
End Sub
Sub CloseWorkbook()
Workbooks("venues_theeway_hours_August2020.XLS").Close SaveChanges:=True
End Sub
Have you tried this ?
ws2.Range("A1:E200").Value = ws1.Range("A1:E200").Value
You're making life quite difficult for yourself there, splitting the code out across 3 subs. Better to
rename the references to make them easier to differentiate source/destination.
keep it all together so the workbooks/worksheets can still be referenced as they're created:
Apologies if I've misread your requirements, my code does the following:
Reads the original workbook, sheet "Reports", range A2 for a filename.
Opens that filename as a 'source' workbook
Copies data from..
that 'source' workbook, sheet "Sheet", range A1:E200
..to original workbook, sheet "HOURS", range A1:E200
and then closes the 'source' workbook, unsaved as you've not made any changes.
Dim wbSource As Workbook
Dim wbDest As Workbook
Dim wsSource As Worksheet
Dim wsDest As Worksheet
Dim strFName As String
Set wbDest = ThisWorkbook
Set wsDest = wbDest.Sheets("HOURS")
strFName = wbDest.Worksheets("Reports").Range("A2").Value
Set wbSource = Workbooks.Open(strFName)
Set wsSource = wbSource.Worksheets("Sheet")
wsDest.Range("A1:E200").Value = wsSource.Range("A1:E200").Value
wbSource.Close SaveChanges:=False
I'm a little puzzled about your workbook close with save? Perhaps you actually want to close the source sheet unsaved and maybe save the destination sheet you're adding data to? In that case you'll need to add this line to the end of the above code.
wbDest.Close SaveChanges:=True
I have to 2 Excel workbooks to work with: Book1october & Book2. Book1october18 is an import file, meaning that it changes monthly, along with the name (next month it will be Book1november18). I have to copy some data from Book1october to Book2 automatically through VBA code.
This is the code that I've written:
Windows("Book1october18").Activate
Sheets("Sheet1").Activate
Range("B2:AQ5").Select
Selection.Copy
Windows("Book2").Activate
Sheets("Sheet1").Activate
Range("R2:BG5").Select
ActiveSheet.Paste
My problem is that I don't know how to write the code in order to make the actions that I want whenever the month's name changes and also the year. (I have to make it for all the months and 2019)
You can automatically update your workbook name using the Date() function and Format()
Dim sWbName As String
sWbName = "Book1" & LCase(Format(Date, "mmmmyy"))
Debug.Print sWbName
'Prints Book1october18
The name/path of the workbook doesn't need to matter. Use K.Davis's code to come up with a filename, or prompt the user for a path/file to open - get that string into some sourceBookPath variable, then have the macro open the workbook. Now you can hold a reference to that Workbook object:
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Now, the worksheet.
Dim sourceSheet As Worksheet
If the sheet is always going to be named "Sheet1", then you can do this:
Set sourceSheet = sourceBook.Worksheets("Sheet1")
Or, if the sheet is always going to be the first sheet in the book (regardless of its name), you can do this:
Set sourceSheet = sourceBook.Worksheets(1)
Once you have a Worksheet object, you can get the Range you need - but first you need your target. Again if "book2" is opened by the macro, things are much simpler:
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
Or is it created by the macro?
Set targetBook = Application.Workbooks.Add
Anyway, we want the first sheet:
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets(1)
And now we can copy from the source, and paste to the target:
sourceSheet.Range("B2:AQ5").Copy targetSheet.Range("R2:BG5")
And not once did we ever need to .Select or .Activate anything, and we never needed to care for any Window.
Replace:
Windows("Book1october18").Activate
with:
s = LCase(Format(Now, "mmmm")) & Right(Year(Now), 2)
Windows(s).Activate
Try this.
This is a recognition of the next month's document, assuming you have opened two documents.
Sub test()
Dim Wb1 As Workbook, wb2 As Workbook
Dim Wb As Workbook
For Each Wb In Workbooks
If InStr(Wb.Name, "Book1") Then
Set Wb1 = Wb
ElseIf InStr(Wb.Name, "Book2") Then
Set wb2 = Wb
End If
Next Wb
Wb1.Sheets("Sheet1").Range("B2:AQ5").Copy wb2.Sheets("Sheet1").Range("r2")
End Sub
I am trying to build a code which would switch to the immediate other open workbook and copy data from there.
I can use workbook(1) and workbook(2) ,but problem is this index changes by sequence of opening workbooks.
So I want to put if function in it ,but doesnt work. Below is the code.
If ActiveWorkbook = Workbooks(1) Then
Workbooks(2).Activate
Else
Workbooks(1).Activate
End If
but it gives error 438 ,object doesn't support property or method.
Can you help me debug this?
Try the code below, the last section of the Copy >> Paste is just an example how you copy Range("A1:E10") from "Sheet1" in DestWB to ThisWB "Sheet1" (without using Activate or Select) - you should be able to modify it quite easily.
Code
Option Explicit
Sub CopyThisWorkBOok()
Dim ThisWB As Workbook
Dim DestWB As Workbook
Dim wb As Workbook
Dim i As Long
i = Application.Workbooks.Count
If i <> 2 Then ' check if number of open workbooks is 2
MsgBox "You need to have 2 open workbooks, currently there are " & i & " open workbooks", vbCritical
Exit Sub
Else
For Each wb In Application.Workbooks ' loop through all open workbooks
If wb.Name <> ThisWorkbook.Name Then
Set DestWB = wb
Else
Set ThisWB = ThisWorkbook
End If
Next wb
End If
' from here you start the part where you copy >> paste, there is no need to `Activate` or `Select` anything
DestWB.Worksheets("Sheet1").Range("A1:E10").Copy Destination:=ThisWB.Worksheets("Sheet1").Range("A2")
End Sub
You can use names of target objects, for example:
Workbooks("MyBook.xls").Worksheets("Sheet1").Activate
Depending on what you are trying to do, the description is not very clear, you can use a variation of this code. You can define the workbook that contains the VBA as "ThisWorkBook" and go from there.
Dim source_worksheet As Worksheet
Set source_worksheet = ThisWorkbook.Worksheets("Sheet2")
Dim target_worksheet As Worksheet
Set target_worksheet = ActiveWorkbook.Worksheets("Sheet1")
'Defines what sheet you are copying
source_worksheet.Copy After:=target_worksheet
The below code attempts to print worksheets across multiple workbooks.
Dim wb1, wb2, wb3 as workbook
set wb1 = workbooks.open(......)
set wb2 = workbooks.open(......)
set wb3 = workbooks.open(......)
Sheets(Array(wb1.Sheets(...),wb2.Sheets(...),wb3.Sheets(...))).PrintOut
There's a TypeMismatch error in my runs on the last line. What am I Mismatching?
As written in the Office VBA Reference, the Sheets-Object refers to
A collection of all the sheets in the specified or active workbook.
Therefore it will not be possible to print sheets from different workbooks together in one print task. Moreover, the syntax ist Sheets(Index) so therefore the index or the name of the sheet has to be passed.
Sub testPrint()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim s(1) As Worksheet
Dim mySheet As Variant
'
' collect sheets from different workbooks
'
Set wb1 = Workbooks("wm1.xlsm")
Set wb2 = Workbooks("wm2.xlsm")
Set s(0) = wb1.Sheets(1)
Set s(1) = wb2.Sheets(1)
'
' print or print preview sheets after each other
'
For Each mySheet In s
mySheet.PrintPreview
Next
End Sub
If You want to print multiple sheets from one workbook in a single print task, You may select them and then print all selected ones.