PasteSpecial of Range class failed - vba

I am trying to select copy everything from a "database" workbook. and paste it in the current workbook, sheet 5. The code I am using is the following.
Sub Import()
Dim DBaseWB As Workbook
Set DBaseWB = Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False)
' set DBaseWB as the database workbook after opening it from sharepoint.
Dim DBaseSheet As Worksheet
Set DBaseSheet = DBaseWB.Sheets(1) 'DBaseSheet is referenced to sheet 1 of Database workbook.
Sheet5.Cells.Clear
DBaseSheet.UsedRange.Copy 'Copy everything from the database
Sheet5.Range("A1").PasteSpecial xlPasteAll 'Paste everything in sheet 5 of current workbook
Application.DisplayAlerts = False
DBaseWB.Close saveChanges:=False
Application.DisplayAlerts = True
End Sub
I am receiving an error when running the following code. Though, sometimes it doesn't give me an error.
Run-time error '1004': PasteSpecial method of Range class failed
I think I know why it's giving me an error at the PasteSpecial line. When I have a different cell selected in sheet 5, it gives me no error. but when I recheck, without selecting any other cell, (so it will have the pasted range selected), I get this error.
I tried using the following line between copy and pastespecial,
Sheet5.range("A1").select
it gives me the same error.
----------UPDATE----------
I first used DisplayName's solution and it worked until yesterday. But this morning, it was causing problems. It another error. Then I tried all other solutions with no luck. all gave me the same errors. I also added the workbook.worksheet to the solutions below giving me no luck. This time the error was with the copy method. I also noticed that lots of columns say #REF.
Versions I tried:
DisplayName's solution combined with thisworkbook.worksheet
Sheet5.UsedRange.Clear
With Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False) 'open and reference your Database workbook
.Sheets(1).UsedRange.Copy Destination:=ThisWorkbook.Sheets(5).Range("A1") ' copy referenced workbook sheet 1 content and paste it to sheet 5
.Close False
End With
Gary's Student's solution combined with thisworkbook.worksheet
Dim DBaseWB As Workbook
Set DBaseWB = Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False)
' set DBaseWB as the database workbook after opening it from sharepoint.
Dim DBaseSheet As Worksheet
Set DBaseSheet = DBaseWB.Sheets(1) 'DBaseSheet is referenced to sheet 1 of Database workbook.
Dim Destination As Worksheet
Set DestinSh = ThisWorkbook.Sheets(5)
Sheet5.Cells.Clear
DBaseSheet.UsedRange.Copy DestinSh.Range("A1").PasteSpecial 'copy database info in planning tool.
Application.DisplayAlerts = False
DBaseWB.Close saveChanges:=False
Application.DisplayAlerts = True
errors:
Run-time error '1004': Copy method of Range class failed

First insure that there are no merged cells on either worksheet, and then try:
DBaseSheet.UsedRange.Copy Sheet5.Range("A1")

you could simply go:
Sub Import()
Sheet5.UsedRange.Clear
With Workbooks.Open("http://collaboration.pwc.ca/team/Plant5EngineLines/Documents/Plant 5 master build plan/Database.xlsm", UpdateLinks:=False) 'open and reference your Database workbook
.Sheets(1).UsedRange.Copy Destination:=Sheet5.Range("A1") ' copy referenced workbook sheet 1 content and paste it to sheet 5
.Close False
End With
End Sub

I am with Bruce Wayne on this one
As you have opened a new workbook the focus is now on that workbook.
If you are trying to clear the cells in the workbook the code resides in (destination) after you have launched a new workbook and switched the focus you will need to reference the original workbook to do so, like this:
ThisWorkbook.Sheets(5).Cells.Clear
Hope this helps

Related

ms-Excel Worksheet transfer between worksbooks and vlookup

I have a simple problem(at least seems to be) that I just cannot seem to be able to find a good solution to:
I have 4 workbooks, that all contain two of the exact worksheets(rest of the worksheets are unique for each workbook). I am storing these two worksheets in a seperate workbook(so 5th workbook). Out of these 2 worksheets, 1 of them is a Data sheet made up of many tables, which I do updates on and the other one is a sheet called V, which just uses some vlookup functions to bring up the related data from this Data sheet.
I am trying to find a way to be able to pass along this data sheet to each individual workbook, instead of editing the data sheet individually for each workbook(All 4 of them).
I was able to come up with the following macro, which checks if the sheet already exists and if it does it deletes it. Then it opens up location of the excel file, copies this worksheet to the workbook and therefore I have the most "updated" version of this data worksheet.
Sub UpdateT()
Sheets("data").Visible = True
Dim wb As Workbook
Dim aw As Workbook
''Open 2nd Workbook
Set aw = Application.ActiveWorkbook
'Check if data worksheet exists, and if it does delete it
If Not GetWorksheet("data") Is Nothing Then
Application.DisplayAlerts = False
Worksheets("data").Delete
Application.DisplayAlerts = True
End If
'Check if T worksheet exists, and if it does, delete it
If Not GetWorksheet("T") Is Nothing Then
Application.DisplayAlerts = False
Worksheets("T").Delete
Application.DisplayAlerts = True
End If
Set wb = Workbooks.Open(Filename:="C:\Users\yilmadu001\Desktop\Update.xlsx")
'Copy To Different Workbook
wb.Sheets("data").Copy _
After:=aw.Sheets("Data1")
wb.Sheets("5120 TI").Copy _
After:=aw.Sheets("MENU5120")
'Close 2nd Workbook
aw.Save
wb.Close
'Hide the data worksheet
aw.Sheets("data").Visible = False
End Sub
'Function to check if worksheets exist
Function GetWorksheet(shtName As String) As Worksheet
On Error Resume Next
Set GetWorksheet = Worksheets(shtName)
End Function
The problem is the following:
When the new Data worksheet is transferred, the V worksheet is no longer working with the Vlookup function to be able to point to the relative information. So then I thought, okay what if I transfer BOTH Data and V worksheets, however that also did not work.
Is there a way to be able to use Vlookup, while copying the Data sheet? (The name is exactly the same I do not understand why it does not seem to be able to point to the cells of the table). It just looks blank, can't point to anything.
NOTE: I am not changing the format of the Data tables, basically just the values, so the format is the exactly the same.
It is probably important to note that the main excel workbooks(the 4) are in use 24/7, therefore I cannot go the other way(Update from Data workbook to the main workbook). I must "pull" the updated worksheet rather than "push".
If anyone has any suggestions I'd really appreciate. Thank you.

VBA to copy and past in two different workbooks

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
.

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

Why are two Excel sheets opening when I try to create one in VBscript?

I have written a program in VBscript to create an excel sheet. The program works fine, and when i click on the Excel sheet to open it, the sheet i created is opened as well as a new excel "Book1". Why is this happening? How can I stop it so that only the sheet i created will open?
Code is given below:
Set objExcel = CreateObject("Excel.Application") 'Bind to the Excel object
objExcel.Workbooks.Add 'Create a new workbook.
Sheet = 1 'Select the first sheet
Set objSheet = objExcel.ActiveWorkbook.Worksheets(Sheet) 'Bind to worksheet.
objSheet.Name = "InfoBook" 'Name the worksheet
strExcelPath = "c:\scripts\InfoBook.xlsx" 'Set the save location
objSheet.Range("A1:C1").Font.Bold = True
objExcel.Columns(3).AutoFit()
objSheet.Cells(1, 1).Value = "Date" 'Row 1 Column 1 (A)
objSheet.Cells(1, 2).Value = "Time" 'Row 1 Column 2 (B)
objSheet.Cells(1, 3).Value = "Category" 'Row 1 Column 3 (C)
objExcel.ActiveWorkbook.SaveAs strExcelPath
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
Have you tried rebooting your computer and running the code again?
The additional workbook may be left over from an earlier, failed, attempt at running the code. Although I cannot replicate the error using just your posted code, I can replicate it by performing
Set objExcel = CreateObject("Excel.Application") 'Bind to the Excel object
objExcel.Workbooks.Add 'Create a new workbook.
and then running your script.
Because the first script creates a workbook but doesn't close the Excel application, when you open the workbook created by your script, the still running instance of Excel is opened (which still contains Book1) and your workbook is also opened.
Rebooting your computer will get rid of the running instance of Excel - or you can just terminate it using Task Manager.
I figured out what the problem is. The line
objSheet.Name = "InfoBook"
creates a workbook with that name. Then when we specify the path for the workbook, we are again creating a workbook of that name in the following line
strExcelPath = "c:\scripts\InfoBook.xlsx"
so the trick is to only name the excel workbook in the path, so it'll only be opened once, and saved where we want it.
Thanks to everyone who spent time on this little predicament of mine. Hope it helped you guys too.

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