VBA to copy and past in two different workbooks - vba

I want to copy all the data and paste it in new workbook. With the below coding, I am able to paste all the values but it is creating two workbooks and pasting the data in one workbook.
I want to create only one new workbook and past the data. Not sure as to what went wrong.
On Error Resume Next
ThisWorkbook.Sheets(2).Copy
Dim wkb As Workbook
Set wkb = Workbooks.Add
wkb(1).PasteSpecial xlPasteValues
On Error GoTo 0

The Copy method has a different meaning when applied to a Worksheet and when applied to a Range:
The Copy method of a Worksheet creates a copy of the sheet; in the absence of any parameter, the copy is placed in a new workbook.
The Copy method of a Range puts a copy of the Range on the clipboard, from where you can then Paste it somewhere else.
So in your case, the statement
ThisWorkbook.Sheets(2).Copy
already makes a copy the Worksheet into a new workbook.
If you want to create the new workbook explicitly then you should copy the used range to the clipboard:
ThisWorkbook.Sheets(2).UsedRange.Copy

It's not the answer, but let me do it instead of yourself:
On Error Resume Next
ThisWorkbook.Sheets(2).Copy
Dim wkb As Workbook
Set wkb = Workbooks.Add
wkb(1).PasteSpecial xlPasteValues
On Error GoTo 0
.

Related

VBA Error Subscript out of range in for loop used to copy/paste

I keep getting an error message for my for loop. What it is supposed to do is compare a variable to the first column for every row for a given worksheet and copy it if it matches, then paste it to a worksheet in a different workbook but for some reason I keep getting "Run-time error '9': Subscript out of Range" for the line referencing the new workbook/worksheet.
My for loop so far:
For i = 1 To Sheets(1).UsedRange.Rows.Count
If Sheets(1).Cells(i, 1).Value Like dateRange & "*" Then
Sheets(1).Rows(i).Copy
Workbooks(destinationWorkbook).Worksheets("Sheet2").Rows(i).Paste 'Debug shows the error is here
End If
Next i
In the previous code I define the variable as:
destinationWorkbook = "C:\Users\lbran\Desktop\Book1.xlsm"
I have also tried using Workbooks(destinationWorkbook).Worksheets("Sheet2").Cells(i, 1).Paste
I'm very new to VBA so I'm not sure if I'm referencing the pasting to worksheet correctly but I know it does exist as a new, empty sheet in the workbook
Once you've opened a workbook it's name is just the filename it was saved under, not the path. So you would do
Workbooks.open(destinationWorkbook)
But then refer to it as
Workbooks("Book1.xlsm")
But I wonder if you are trying to copy to a new workbook that isn't on your hard drive? In which case you would write
Workbooks.add
WorkBooks("book1")
There wouldn't be a file extension because you haven't saved it yet.
You can avoid all these problems by using an object variable
Dim wb as workbook
Set wb = workbooks.open(destinationworkbook)
or
Set wb = workbooks.add
and then just wb to refer to the workbook

Copy and moving an entire sheet to another workbook. 1mil rows to 65536 rows

The following is part of my code that involves copying an entire named sheet from one master file to a new unsaved file that's being worked on:
ActiveWorkbook.Sheets("VehicleList").Copy _
After:=Workbooks(2).Sheets(1)
So this worked fine to place the sheet into workbook 2 but now the files we're dealing with are in old excel mode which is throwing up the following error due to old excel having less rows:
"Excel cannot insert the sheets into the destination workbook, because it contains fewer rows and columns"
How can I tweak the copy and pasting into Workbooks(2) without breaking the code? I thought defining a range of 1000 rows to copy and move would work, but this also gave an error. Thanks for your help.
Assuming you just want the values (i.e. I'm speeding it up by not doing a copy paste) you can do:
Workbooks(2).Sheets.Add After:=Sheets(1)
Workbooks(2).Sheets(2).Range("A1:F1000").Value = ActiveWorkbook.Sheets("VehicleList").Range("A1:F1000").Value
I'd go like follows
Option Explicit
Sub main()
Dim targetWs As Worksheet
With Workbooks("MyWorkbookname").Sheets("VehicleList") '<--| fully qualify reference wanted worksheet in the wanted workbook
Set targetWs = SetOrGetSheet(Workbooks(2), .name) '<--| get the (new) target worksheet on the target workbook named after referenced sheet
Intersect(.Range("A1:F1000"), .UsedRange).Copy targetWs.Cells(1, 1) '<--| copy range to target worksheet on the target workbook
If targetWs.name <> .name Then MsgBox "a new sheet has been created in " & targetWs.Parent.name & " with name " & targetWs.name
End With
End Sub
Function SetOrGetSheet(targetWb As Workbook, shtName As String) As Worksheet
targetWb.Worksheets.Add '<--| add a new sheet in the target workbook
On Error Resume Next
Set SetOrGetSheet = targetWb.Worksheets(shtName) '<--| try and get any possible target workbook sheet with the passed name
If SetOrGetSheet Is Nothing Then targetWb.ActiveSheet.name = shtName '<--| if target workbook has no worksheet with passed name then name the new one after it
Set SetOrGetSheet = targetWb.ActiveSheet 'return the new worksheet
End Function
should you be afraid your range-to-copy could exceed 65 rows and/or 256 columns than you should add its size check
edit for values pasting only
should you be interested in pasting values only then you can go like follows:
Sub main()
SetOrGetSheet(Workbooks(2), "VehicleList").Range("A1:F1000").value = ActiveWorkbook.Sheets("VehicleList").Range("A1:F1000").value '<--| copy values form source to target worksheet
End Sub
while SetOrGetSheet() function stays the same as above
as you may have guessed that function is there for a more general approach where you may want (or just have) to handle the possibilty of target workbook having a worksheet named after "VehicleList" already

Copy a range from excel to another workbook in a new worksheet

I'm very new to VBA macros and have taught myself some code but I'm struggling with my current piece of work and can't find the answer I am looking for.
I want to copy a range of cells (B3:N21) from one workbook to another "master" workbook - which seems simple enough - but I would like it to copy into a blank/new worksheet in the Master copy every time the Macro is run.
The range contains formulas, I would only need the values copied to the Master workbook.
Any help with this would be greatly appreciated.
Thanks
Worksheets("Sheet1").Range("C1:C5").Copy
Worksheets("Sheet2").activate
Worksheets("Sheet2").Range("D1:D5").PasteSpecial _
Operation:=xlPasteSpecialOperationAdd
End With
I think you only need paste special, this is an example
try this
Option Explicit
Sub main()
Dim masterWb As Workbook
Dim mySht As Worksheet
Set mySht = ThisWorkbook.ActiveSheet '<~~ assuming you're copying values from active worksheet of the workbook the macro resides in
' beware: if you start the macro while the active sheet is not the one you want, this will lead to unespected results
Set masterWb = Workbooks("Master") '<~~ Change "Master" with whatever name your master workbook must have
' beware: we're assuming "Master" workbook is already open, otherwise this line will throw an error
With masterWb.Worksheets.Add
.Range("B3:N21").Value = mySht.Range("B3:N21").Value
End With
End Sub
mind the comments
the code above can be reduce to a much less verbose (and self explanatory, too) one like follows
Sub main2()
Workbooks("Master").Worksheets.Add.Range("B3:N21").Value = ThisWorkbook.ActiveSheet.Range("B3:N21").Value
End Sub
where apply the same comments of the lengthy code, which is:
assuming you're copying values from active worksheet of the workbook the macro resides in
beware: if you start the macro while the active sheet is not the one you want, this will lead to unespected results
change "Master" with whatever name your master workbook must have
beware: we're assuming "Master" workbook is already open, otherwise an error would be thrown

Dealing with Run-time error '9': Subscript out of range when iterating over Worksheet

Not an Excel/VB expert but I keep getting
Run time error: 9: Subscript out of range
The error is occurring at the For Each line. Not sure why. I'm trying to copy worksheets from one workbook to another workbook.
The Workbook strFileName is being open successfully and the workbook does contain two other worksheets but code is failing on next line. I've seen similar posts regarding similar issue but have not had any luck. Any advice would be great. (I'm using Excel 2010) Thanks
Workbooks.Open (strFileName)
For Each sheet In Workbooks(strFileName).Worksheets
total = Workbooks(activeWKBook).Worksheets.Count
Workbooks(strFileName).Worksheets(sheet.Name).Copy _
after:=Workbooks(activeWKBook).Worksheets(total)
Next sheet
strFileName contains the full path of the workbook.
So you cannot use it in Workbooks(strFileName) since it only expects the workbook name.
This is how you should do it:
Dim wbName As String
wbName = Split(strFileName, "\")(Ubound(Split(strFileName, "\"))) ' Get the WB Name
For Each sheet In Workbooks(wbName).Worksheets
' Other cool stuff goes here
Next
But it is better to be explicit right away so you'll not have to worry about default path separator.
Remember that it is not always \. So I suggest you try below.
Dim myWB As Workbook
Set myWB = Workbooks.Open(strFileName)
Dim sheet As Worksheet
For Each sheet In myWB.Worksheets
With Thisworkbook ' Explicitly refer to the workbook that contains the code
sheet.Copy After:=.Sheets(.Sheets.Count)
End With
Next
Remember, you need to use ThisWorkbook in place of ActiveWorkbook.
Why? Because the moment you open the other workbook, the currently opened workbook becomes the ActiveWorkbook.
So to copy all sheets from the opened workbook to the workbook that contains the code, use ThisWorkbook instead.

Copy appended data to a different worksheet

I have the following which is working in the same workbook how do I get this to use a summary sheet in a different workbook?
Sub SummurizeSheets()
Dim ws As Worksheet
Application.ScreenUpdating = False
Sheets("Summary").Activate
For Each ws In Worksheets
If ws.Name <> "Summary" Then
ws.Range("D2:D6, D8:D15").Copy
Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).PasteSpecial (xlPasteValues)
End If
Next ws
End Sub
Make sure you place the sub-routine in a Module, and not in
ThisWorkbook. You can insert a new module by right-clicking on workbook name (from the VBA editor) and going to Insert > Module.
Make sure the workbooks you want to use/reference are open.
Make sure the workbooks are all located in the same workbook collection. This is not a problem unless you manually create an additional instance of Excel.
Reference the workbooks using the Workbooks() object just like you
do with Worksheets.
Sub test()
Dim b2 As Workbook 'We will use this variable as a reference to the external workbook that contains the "Summary" worksheet.
Set b2 = Excel.Workbooks("testbook2") 'We assign the external workbook (which I named "testbook2" for the purposes of this example) to our 'b2' variable.
Dim ws1 As Worksheet
Dim ws2 As Worksheet 'We will use these variables as references to the worksheets we're using.
Set ws1 = Excel.ActiveSheet 'We set ws1 to equal our current sheet (which presumably is where you'll be copying data from).
Set ws2 = b2.Worksheets("Summary") 'We set ws2 to equal the sheet (named "Summary") in the external workbook (named "testbook2").
ws1.Range("D2:D6").Copy 'We copy the data from the active sheet, which we reference using our 'ws1' variable.
'Note: I had issues with using multiple ranges in the same object so I removed this from your code.
ws2.Cells(Rows.Count, 4).End(xlUp).PasteSpecial xlPasteValues 'You only need to use the ws2 variable since we've already defined it as the "Summary" sheet you want.
End Sub
I'm not sure why I follow that first rule, but I seem to remember having issues when using ThisWorkbook in conjunction with external workbook references.
Update
I edited the code to show you a better example of how to do this. You almost never need to use "Activate" or "Select" commands in VBA. Just assign variables and reference the values directly.