Run-time error '1004': Copy method of Range class failed Excel 2013 when adding a new pivot table - vba

I am getting the error specified in the title of this issue when trying to copy and paste some columns (and it's data) to a new workbook.
The code below used to work till the moment when I add a new sheet with a new pivot table in my workbook, and I don't know the reason:
Sub ExtractData_2()
Workbooks.Add
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\extract_Fcst" & ".csv", 6
ThisWorkbook.Worksheets("Forecast Enrichment").Activate
ThisWorkbook.Sheets("Forecast Enrichment").Range("E:S").Copy Destination:=Workbooks("extract_Fcst.csv").Sheets(1).Range("A:O")
Workbooks("extract_Fcst.csv").Sheets(1).Range("A:O").EntireColumn.AutoFit
End Sub
Does anybody have any idea to how to solve that problem? I have tried a lot of different solutions found in google but any of it works!

Use object variables and assign properly, then break up your copy/Destination to see whether the error raises on the Copy or the Paste, as follows:
Sub ExtractData_2()
Dim csvWorkbook as Workbook
Set csvWorkbook = Workbooks.Add
csvWorkbook.SaveAs ThisWorkbook.Path & "\extract_Fcst" & ".csv", 6
' Unnecessary to "Activate" the sheet...", so you can delete this:
' ThisWorkbook.Worksheets("Forecast Enrichment").Activate
'Try using copy/paste as separate statements to see where the failure may occur
ThisWorkbook.Sheets("Forecast Enrichment").Range("E:S").Copy
csvWorkbook.Sheets(1).Range("A1").Select
csvWorkbook.Sheets(1).Paste
csvWorkbook.Sheets(1).Range("A:O").EntireColumn.AutoFit
End Sub
If it still raises the error, let me know which line it happens.

Related

How to open and activate another workbook in VBA?

I'm creating a macro where I will need to run it in 1 file (called "Masterfile"), it will open and execute the macro on another file ("SurveyReport") and then give me a message box saying "done!".
The code I have to execute on the SurveyReport file works fine when I open that file manually and execute it. The code I need to open SurveyReport from MasterFile is also working it seems, I ran the below with no issues:
Sub PivotTable()
'
' PivotTable Macro
Dim MasterFile As String
MasterFile = ActiveWorkbook.Name
Dim SurveyReport As String
SurveyReport = Application.GetOpenFilename("Excel files (*.xlsx), *xlsx", 1, "Please select the Survey Create Report file", , False)
Workbooks.Open (SurveyReport)
End Sub
But, when I try to activate the SurveyReport file so I can begin executing the macro in it, I get a "Subscript out of range" error. I've tried using the following code after the above block and before the code to execute in the SurveyReport file:
Windows(SurveyReport).Activate
This didn't work, not did:
ThisWorkbook.Activate
...which only had the effect of activating the MasterFile.
SurveyReport file is a .xlsx file. I tried saving it as a .xls file and amending the code, but no joy.
I also tried passing it the file name directly (i.e. Windows("filename.xlsx").Activate), same issue.
ActiveWorkbook is as it says on the tin - whichever workbook happens to be active when the code runs.
ThisWorkbook is always the workbook that the code is sitting in.
You can SET references to specific workbooks rather than just using their names each time. A name can change, or reference the wrong object.... imagine you have a friend called Darren. Each time you mention him you mention him by name. Someone that doesn't know Darren hasn't a clue which Darren out of all the ones available in the world you're talking about. Now imagine you have a little replica of Darren in your pocket... nah, that's a terrible anology - it wouldn't be a replica, it would be a reference to the real Darren... anyway, I digress.
This code sets a reference to the workbook, you can then use that reference any time you want to refer to the correct workbook:
Sub PivotTable()
Dim MasterFile As Workbook
Dim SurveyRptName As String
Dim SurveyReport As Workbook
Set MasterFile = ThisWorkbook '
SurveyRptName = Application.GetOpenFilename("Excel files (*.xlsx), *xlsx", 1, _
"Please select the Survey Create Report file", , False)
If SurveyRptName <> "False" Then
Set SurveyReport = Workbooks.Open(SurveyRptName)
End If
SurveyReport.Activate 'You don't need this line. It doesn't matter if
'the workbook is active, the code knows which one
'you're talking about in the next line.
MsgBox "This is " & SurveyReport.Name & _
" containing " & SurveyReport.Worksheets.Count & " sheets." & vbCr & _
"The value in cell A1 of the first sheet is " & _
SurveyReport.Worksheets(1).Range("A1")
End Sub
Edit: Of course, if you press Cancel when selecting a file then the lines following the IF...THEN code won't have a reference to work on and you'll get a Object Variable or With block variable not set - best not to run the bottom bit of code if you haven't successfully opened the Survey Report file.
The part of the answer that is missing - is that he tried to call a method of an object when his variable was STRING - the open command and subsequent commands will give you an OBJECT - which has properties and methods like .Activate. The STRING type has no such method or property (to be sure - it may have others).
the solution provided by Darren solves this by declaring his SurveyReport as type Workbook - an object of Excel.

Method 'SaveAs' of object '_Workbook' failed VBA

I have a workbook that is connected to a database and when you refresh the workbook, it refreshes your data in the workbook. Afterwards a macro is ran to save the new (raw) data in two different locations, then the macro will do analysis on that raw data, and save the same workbook later on in 4 other locations.
When I am trying to do the first save of the raw data, I am able to save to the first location, but when it moves to the second location I am getting the error: Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed. Both of the locations are valid locations.
Here is one sub in the macro that does the first file save:
Sub saveraw()
Dim rdate As String
Dim rawfilename As String, rawfilename1 As String
Dim mywb As Workbook
Set mywb = ActiveWorkbook
rdate = Format(Now(), "mm-dd-yy")
rawfilename = "\\sw\mes\PS\SC\SCM_Supply_Execution\Spares\This Weeks Number Database\This Weeks Numbers(raw) " & rdate & ".xlsm"
rawfilename1 = "\\sw\mes\PS\SC\SCM_Shared\Spares Reports\This Weeks Numbers(raw) " & rdate & ".xlsm"
mywb.Save
Worksheets("Sheet2").Range("A2") = Null
Application.DisplayAlerts = False
mywb.SaveAs Filename:=rawfilename
mywb.SaveAs Filename:=rawfilename1
Application.DisplayAlerts = True
End Sub
I have also tried using the method of
ActiveWorkbook.SaveAs
in place of both of the mywb.SaveAs, but that did not work either.
As a test, run the code against file locations only YOU have access to. I'm noticing a reference to shared drive on the second command so maybe someone is already in it and it can't be saved over.
Set display alerts to true for now.
Also, When you run the test macro, make sure you don't have any windows explorer windows open and feed back here with results and I'll assist if it debugs again.
On the face of it, the code looks good to me.
Try this
ActiveWorkbook.SaveAs Filename:="\\sw\mes\PS\SC\SCM_Supply_Execution\Spares\This Weeks Number Database\This Weeks Numbers(raw) " & rdate & ".xlsm" _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled
This might have issues if the file already exists because then a pop-up will ask you if you want to overwrite it or not
Though I think the error is due to an issue with privileges in that specific location or connection issues

Run Time error 1004: Select Method of Worksheet class failed with (varCellContent.Parent.Name)

The code edits, then copies data from a temporary sheet to the current workbook. I am using varCellContent to ask the user to choose the source sheet. I had no trouble when testing the code as I was building it by using F8 to step through (and the code still works perfectly like this).
But when I run the macro normally, I am getting
Run Time error 1004: Select Method of Worksheet class failed
on the following line:
Workbooks(varCellContent.Parent.Name).Worksheets("Sheet1").Select
The following may not be relevant to the cause of the problem but I have read a bit about it while searching for an answer.
It sounds like using .Select is not a good idea, but there are 2 reasons I thought it was useful in this situation.
I don't have to name the sheet for each of the following rows of code that delete and move the columns.
When building and debugging the code I wanted the sheet to be visible so that I could see what was happening as I stepped through each line of code.
So taking those 2 reasons into account is there still a better way to avoid using .Select?
Sub ImportNewData()
'
'
' Import data, save as new workbook
Dim LR As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
' Clear data
Range("A3:I" & LR).ClearContents
' User choose source sheet
Dim varCellContent As Worksheet
Set varCellContent = Application.InputBox _
(prompt:=" " & vbNewLine & "Click any cell in the Aged AP Summary that has been exported from Systematic to Excel, then click OK", Type:=8).Parent
Workbooks(varCellContent.Parent.Name).Worksheets("Sheet1").Select
'Delete unrequired columns
Columns("E:I").Select
Selection.Delete Shift:=xlToLeft
Worksheets("Sheet1").Activate
Columns("E:I").Delete Shift:=xlToLeft

Excel VBA Run Time Error 1004 "Application-Defined or Object-Defined Error"

I am writing a program that currently, when the user clicks "OK", saves the current file, copies certain values in the file; then pastes the values to a different file. Then both files close. My problem is that it gives me an error:
Run Time Error: 'Application-Defined or Object Defined Error'
It highlights this line:
ThisWorkbook.Worksheets("data").Range("C31", Range("C106").End (xlToRight)).Copy
I separated this line and the one right after it to test it alone and it worked like I wanted to. I tested the rest of the program without those two lines and it worked like I expected it to.
I tried to limit it to just copying one cell and it worked.
I made sure that the name of the sheet was correct.
I tried to just copy one row:
Range("C31", range("C31").End(xlToRight))
it still did not work and I came across the same error message.
I want to say I referenced something wrong but I don't see it.
Any reply at all would be helpful, Thank you.
P.S. I am sorry for redundancy in the code, I don't use "Dim" as much as I should.
Sub Button425_Click()
Dim FName As String
Dim FPath As String
Dim yourmsg As String
Dim testmsg As String
yourmsg = "Are you sure that you want to save and exit?"
testmsg = MsgBox(yourmsg, vbOKCancel + vbExclamation)
FPath = "I:\a\d\f\daily log recycle\"
FName = Sheets("Sheet1").Range("C3").Text
If testmsg = 1 Then
ThisWorkbook.SaveAs filename:=FPath & "\" & FName
Workbooks.Open ("I:\a\d\f\new daily log 1.xlsm")
ThisWorkbook.Worksheets("data").Range("C31", Range("C31").End(xlToRight)).Copy
Workbooks("new daily log 1.xlsm").Worksheets("data").Range("D31").PasteSpecial xlPasteValues
ThisWorkbook.Worksheets("sheet1").Range("E45").Copy
Workbooks("new daily log 1.xlsm").Worksheets("sheet1").Range("E44").PasteSpecial
Workbooks("new daily log 1.xlsm").Worksheets("sheet1").Range("E45").ClearContents
Workbooks("new daily log 1.xlsm").Save
Workbooks("new daily log 1.xlsm").Close
ThisWorkbook.Saved = True
Application.Quit
Else 'do nothing
End If
End Sub
You're mixing a fully addressed range
ThisWorkbook.Worksheets("data").Range("C31"
with a relatively addressed range
Range("C106").End (xlToRight)
Try
ThisWorkbook.Worksheets("data").Range("C31", ThisWorkbook.Worksheets("data").Range("C106").End (xlToRight))
I see a couple of issues:
FPath = "I:\a\d\f\daily log recycle\"
ThisWorkbook.SaveAs filename:=FPath & "\" & FName
When you attempt to save you will have ...\daily log recycle\\<filename>. Remove one of the backslashes \, I'd suggest removing the one in the .SaveAs line.
Then, with these two lines:
Workbooks.Open ("I:\a\d\f\new daily log 1.xlsm")
ThisWorkbook.Worksheets("data").Range("C31", Range("C31").End(xlToRight)).Copy
The ThisWorkbook probably isn't pointing to the one you think it is. On all the following lines you specify Workbooks("new daily log 1.xlsm")., why don't you replace ThisWorkbook with an explicit Workbooks("...") so you can be 100% certain of which of the two open workbooks you're referencing.
I would also do that for these two lines:
ThisWorkbook.Worksheets("sheet1").Range("E45").Copy
ThisWorkbook.Saved = True
Also, just to be clear, ThisWorkbook.Saved = True tells Excel to not prompt you to save the workbook when you close it, but it doesn't actually save the workbook. If you want to actually save it, you'll need to use .Save, just like you do a couple lines above that for Workbooks("new daily log 1.xlsm").Save.

Excel 2010 VBA: .Names.Add does not work after .Hyperlinks.Add

I have run into a problem in Excel 2010 VBA on Windows 7 64-bit version which I have not been able to solve. The issue can easily be recreated by pasting the code below in a module in a new workbook and run it.
What I want to do is to loop through a number of sheets and add a defined name and a hyperlink on each sheet.
Sub Test()
Dim i As Integer
Dim ws As Worksheet
Dim defName As String
For i = 1 To 2
Set ws = Sheets(i)
defName = "Name_" & ws.Name
ws.Names.Add Name:=defName, RefersToR1C1:="=OFFSET(Sheet3!R1C1,0,0,1)"
ws.Hyperlinks.Add Anchor:=ws.Range("A1"), _
Address:="", SubAddress:="=Sheet3!A1"
Next i
End Sub
Running the code gives the following error on the second iteration, on the ws.Names.Add call: Run-time error '1004: The formula you typed contains an error.
Doing any of the following makes the error disappear:
Change the for iteration to "i = 1 To 1" or "i = 2 To 2"
Put a debug breakpoint inside the for loop and pressing F5 when it has stopped
Change the cell reference to
ws.Names.Add Name:=defName, RefersToR1C1:="=Sheet3!R1C1", i.e. removing the OFFSET command
Adding DoEvents to the first line of the for loop or setting Application.EnableEvents = False does not solve the problem.
Does anyone know the cause of this error or how to get around it? I am thankful for any help.
Edit: The issue occurs no matter what the hyperlink links to. Changing the hyperlink to the following does not solve the issue
ws.Hyperlinks.Add Anchor:=ws.Range("A1"), Address:="http://www.google.com"
Edit2: Managed to recreate the issue with an even simpler code:
Sub Test()
With Sheets(1)
.Hyperlinks.Add Anchor:=.Range("A1"), Address:="http://www.google.com"
.Names.Add Name:="myDefName", RefersToR1C1:="=OFFSET(Sheet1!R1C1,0,0,1)"
End With
End Sub
I solved this by separating the for loops into two loops, one for the .names.add calls and one for the hyperlinks.add calls. This way all the names get defined before the first hyperlink is created.
Sorry if it is not correct of me to post this as an answer.