Excel VBA - runtime error 1004 when simplifying recorded code - vba

I've got a recorded macro that I tried to simplify by getting a number of activate and select statements onto a single line, but that results in a runtime error.
This is not a critical problem, but I'm just curious to understand what is going on. This is my initial code snippet (it is preceded by a Copy snippet in the procedure):
ThisWorkbook.Activate
Sheets("MS Act Report").Select
Range("G1").Select
ActiveSheet.Paste
this is my simplified code:
ThisWorkbook.Activate
Sheets("MS Act Report").Range("G1").Select
ActiveSheet.Paste
When running this I get a
runtime error '1004': Select method of Range class failed

You can only select ranges on the active sheet. If "MS Act Report" is not the active sheet, you can't issue a .select command against its cells. To simplify the code, instead of copy-pasting, just make the ranges equal.
Thisworkbook.WorkSheets("MS Act Report").Range("G1:I5").Value= _
ActiveWorkbook.Worksheets("Whatever").Range("a1:c5").Value
Some recommended reading: How to avoid using select

Related

Run-Time Error '1004' in VBA Subroutine

There seems to be something wrong with one of my Excel Objects. Take a look at the below snippet. I created the subroutine Run_all(), and when I step through, it'll go up to the Function row_count() and start executing, however, when it gets to the first highlighted row, I get the error.
**The Sheet that I'm referencing in the function is typed correctly. For example, if I run the bottom subroutine CA_Copy_Paste_, it works correctly and I get no errors.
Why is Excel not recognizing "Sheet 3" in the function? For more context, it only works if I type "Sheet4". Does not work on "Sheet1" or "Sheet2" either.
If you insist on using .Select and .Activate to accomplish your goals then you must activate the worksheet before activating or selecting a cell or range of cells on that worksheet.
worksheets("sheet 3").activate
activesheet.range("c4").activate
If you wish to use some 'shorthand' to try and accomplish this in a single line of code then switch to the Application.GoTo method.
Application.Goto reference:=worksheets("sheet 3").range("c4")
In any event, you are best off avoiding the use of select and activate. See
How to avoid using Select in Excel VBA.

Attempt to reference a sheet yields "Run Time Error 1004"

I'm just trying to select a column so that I can change the date format. I have no idea why, but my code is giving me a huge issue anytime I try to reference the sheet the column is in. But what I don't understand is that many times earlier in my code I successfully reference the sheet with no issues.
Has anyone seen this?
Did VBA just forget about me defining and setting my variable?
Here's an example of my code:
Dim wbPrescrub As Workbook, wsPrescrub As Worksheet
Set wbPrescrub = ThisWorkbook
Set wsPrescrub = wbPrescrub.Sheets("PreScrub")
wsPrescrub.Range("A1").AutoFilter Field:=5, Criteria1:=(""), _
Operator:=xlFilterValues
wsPrescrub.Range("E2:E" & pslastRow).SpecialCells (xlCellTypeBlanks).EntireRow.Delete
wsPrescrub.AutoFilterMode = False
wsPrescrub.Columns("F:F").EntireColumn.AutoFit
wsPrescrub.Columns("F:F").Select
Selection.NumberFormat = "mm/dd/yyyy"
I included lines of my code which worked fine, it is the last two lines that are giving me trouble. I cannot get past the wsPrescrub.Columns line. If I run the code without referencing the sheet it works perfectly fine on the ActiveSheet and correctly selects the column and format. But the second I add in what sheet to look at I get:
Run Time Error 1004: Application-defined or object defined error

Excel 2010 PasteSpecial method of range class failed

I am attempting to understand why a certain bit of code will not work in Excel 2010.
I have a file where cells A1:K200 are part of a table (the Format as Table option form the Home tab), but rows 2-13 are hidden for use with data validation combo boxes. Header row and row banding options are enabled. What I want to do is copy (via the user pressing Ctrl-C) and paste (via user pressing Ctrl-V) data from another workbook and then have a macro function in Worksheet_Change that will transpose the data (based on the value of a checkbox on the worksheet) and paste only the values. Columns A-H will be filled out with other data.
I have disabled events and screen updating, set up a range for cells I14:I200 as StdCost for an intersect function and then have the following code to trap changes to the above range. optTranspose is a checkbox I have placed on the sheet and Target is the variable set up by Excel as part of the Worksheet_Change function.
If Not Application.Intersect(Target, StdCost) Is Nothing Then
If Application.CutCopyMode = xlCopy Then
Application.Undo
.Range("I" & Target.Row).PasteSpecial Paste:=xlPasteValues, Transpose:=optTranspose
End If
End If
The above code will work, but based on my testing it will only work with a maximum of 4 values being pasted in OR it will work if I paste starting on row 15 or below. However, if I paste 5+ values I get the error from the subject
PasteSpecial method of range class failed
From my testing, what appears to happen is that before the undo operation kicks in, Excel automatically adds Column1 and Column2 to columns L and M, which then causes Target to take on "Column1" and "Column2" and thus ends up causing the error when I try and run it on the actual values I want to paste. If I convert the table to a normal range, everything appears to operate as expected.
I want to understand why "Column1" and "Column2" are being inserted by Excel, why it's only at 5+ cells from another spreadsheet that it becomes and issue and how I might be able to account for this in my code.
I want to understand why "Column1" and "Column2" are being inserted by Excel,
This happens when you paste data adjacent to an existing ListObject table.
The change event occurs (i.e., you "Paste" the data), the worksheet changes, and then, the Worksheet_Change event fires.
The error seems to happen because Application.Undo is undoing the Paste operation and further affecting the Application.CutCopyMode = False, so on the next line when you attempt to use the PasteSpecial method, there simply is nothing that can be pasted, because the Undo has cleared it.
Pastespecial seems to be very sensitive to the parameters it's fed.
I was experiencing exactly the same error message from code that had worked before migrating to Windows 10. I found this combination of parameters worked in my case:
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Can't claim that I found that combo of parameters- it came from yactici's self answer
Kudos to yactici for returning to his initial problem despite having a workaround and directly resolving the problem with pastespecial.

Copying information from a separate workbook in Excel VBA

I want to copy the information from cells A2 to A4 into my current workbook and am using the following code to do so, however, when I run the macro I get the message: Run-time error '9', subscript out of range. How do I make it in the range?
Application.Workbooks("Client and Project Droplist").Worksheets("Sheet1").Range("A2:A4").Select
Selection.Copy
Me.Range("A1").Select
ActiveSheet.Paste
UPDATE
I've made it so that it will select the range but now I am getting run-time error 13: Type mismatch. Here is the new code
Private Sub Macro_Click()
Application.Workbooks("Client and Project Droplist").Activate
Application.Workbooks("Client and Project Droplist").Worksheets("Sheet1").Select
Application.Workbooks("Client and Project Droplist").Worksheets("Sheet1").Range("A2:A4").Select
Selection.Copy
Workbooks("VBA Exercises").Worksheets(Sheet1).Select
'Workbooks("VBA Exercises").Worksheets(Sheet1).Range("A1").Select
'ActiveSheet.Paste
End Sub
I commented the last two lines because I haven't quite gotten there yet.
This worked for me. It looks like you have to specify the actual filename, and when you tried to paste it to your active workbook, it wasn't truly active.
Application.Workbooks("client and Project Droplist.xlsx").Worksheets("Sheet1").Range("A2:A4).Select
Selection.Copy
Application.Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1").Select
Selection.Paste

Excel 2013 VBA clear active filter

I need to clear any active filters from a sheet before running a certain macro, this line works just fine IF there is an active filter on
If ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData
However if no filters are selected it returns the error
Runtime error '1004';
ShowAllData method of Worksheet class failed
I got that code from an answer to this question
Excel 2013 VBA Clear All Filters macro
However that question doesn't explain how to ignore the line if no filters are active.
How do I ignore this line if there are no currently active filters applied?
EDIT
For example, all column headings have been auto filtered, so if my sheet is filtered by 'Female' for example I need to remove that filter before running the macro, however if no filters have been applied, just run the macro as normal
Use FilterMode instead of AutoFilterMode. I have dealt with filters frequently and this code works fine.
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
Make sure the worksheet is not protected as this also gives the 1004 error.
I sincerely admire your desire to program for specific circumstances but I have to admit that the quickest way to accomplish this is with On Error Resume Next.
On Error Resume Next
ActiveSheet.ShowAllData
On Error GoTo 0
You shouldn't have to break something to check if it exists but in VBA that is occasionally the best recourse. Personally, I rank On Error Resume Next right up there with SendKeys as a programming method.
The above method does not require that you check to see if .AutoFilterMode is True.
I know this is a relatively old post and don't really like being a necromancer... But since I had the same issue and tried a few of the options in this thread without success I combined some of the answers to get a working macro..
Hopefully this helps someone out there :)
Sub ResetFilters()
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
Next 'Check next worksheet in the workbook
Next
End Sub
** Possible duplicate of thread: Excel 2013 VBA Clear All Filters Macro