Run-error 1004 -- ActiveSheet.Paste - excel

I've recorded this macro, it keeps bugging on the ActiveSheet.Paste. Can someone help me please?
thank you
Sub Macro13()
'
' Macro13 Macro
'
'
ActiveSheet.Range("$A$3:$L$10001").AutoFilter Field:=6, Criteria1:="O/S"
Columns("A:E").Select
Range("A2").Activate
Selection.Copy
ActiveSheet.Range("$A$3:$L$10001").AutoFilter Field:=6
Workbooks.Add
ActiveSheet.Paste
Cells.Select
Cells.EntireColumn.AutoFit
Rows("1:1").Select
Selection.RowHeight = 89.25
Range("G7").Select
Windows("Test.xlsm").Activate
End Sub

First of all I recommend to read How to avoid using Select in Excel VBA which is absolutely necessary to follow strictly if you are a beginner. This makes your code a lot faster and cleaner.
Yes I know this is a recorded macro, and yes they always have a lot of .Select. This is why you should always re-write your recordings to get a good clean and reliable code. But recordings are good to have something to start with.
Then it is better to specify a worksheet by its name and avoid ActiveSheet where ever you can.
Also always specify a worksheet for every Range() or Cells() etc. Otherwise Excel guesses which worksheet you mean and Excel might guess something different from your guess and then fails.
So the code you tried would better look like this …
Option Explicit
Public Sub DoMyStuff()
Dim wsSrc As Worksheet
Set wsSrc = ActiveSheet 'better specify sheet by name: Set wsSrc = Worksheets("SheetName")
Dim wsNew As Worksheet
Set wsNew = Workbooks.Add().Worksheets(1) 'get first worksheet of a new added workbook
wsSrc.Range("$A$3:$L$10001").AutoFilter Field:=6, Criteria1:="O/S"
wsSrc.Columns("A:E").Copy wsNew.Range("A1") 'copy from source sheet directly into the new sheet
wsNew.Cells.EntireColumn.AutoFit
wsNew.Rows("1:1").RowHeight = 89.25
End Sub

Related

How to Copy data from Source to multiple Destination File if Macros code is in Source file?

Suppose I have Source.xlsm( it has only one sheet file) ,it has data in that sheet. and I have 10 different destination.xlsx file in that we have multiple sheets suppose abc, efg, ijk. I have to copy whole data present in Source.xlsx file to 10 different destination excel (under sheet_name ijk).
I want to have macro code in source.xlsm when i click on the button it should copy whole data to 10 different destination files(under sheet_name ijk).
stuck for days please help me
Private Sub CommandButton1_click()
Dim wb As Workbook
Dim lRow As Long
Dim lcol As Long
Dim total As String
ThisWorkbook.Worksheets("ViewList").Select
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lcol = Cells(1, Columns.Count).End(xlToLeft).Column
Range(Cells(1, 1), Cells(lRow, lcol)).Copy
Set wb = Workbooks.Open("C:\Users\Desktop\Destination.xlsx")
wb.Worksheets("abc").Activate
ActiveSheet.Paste
ActiveWorkbook.Save
ActiveWorkbook.Close savechanges = True
ThisWorkbook.Worksheets("ViewList").Activate
ThisWorkbook.Worksheets("ViewList").Cells(1, 1).Select
Application.CutCopyMode = False
End Sub
This code is pasting data in the middle of destination file i want to paste it in from cell (1,1)
I recommend the following
Private Sub CommandButton1_click()
Dim wsViewList As Worksheet
Set wsViewList = ThisWorkbook.Worksheets("ViewList")
Dim lRow As Long
lRow = wsViewList.Cells(wsViewList.Rows.Count, 1).End(xlUp).Row
Dim lcol As Long
lcol = wsViewList.Cells(1, wsViewList.Columns.Count).End(xlToLeft).Column
Dim wb As Workbook
Set wb = Workbooks.Open("C:\Users\Desktop\Destination.xlsx")
wsViewList.Range("A1", wsViewList.Cells(lRow, lcol)).Copy Destination:=wb.Worksheets("abc").Range("A1").Paste
'wb.Save 'this statement is not needed because you save on closing the workbook. Otherwise you would save twice which takes twice the time.
wb.Close SaveChanges:=True
wsViewList.Cells(1, 1).Select 'this is actually not needed unless you want to move the users view to that cell. If that is not what you need remove that line.
Application.CutCopyMode = False
End Sub
Your code would work without any .Select or .Activate statements. Also your code needs to know where exactly you want to paste so you should specify the destination cell not only the worksheet. Also it is a good practice do do the copy and past in one statemant or at least don't do any further steps between copy and paste because that can interfere with the copyied range.
Finally named parameters need to be submitted with := not with = sign. I highly recommend you to activate Option Explicit because the line
ActiveWorkbook.Close savechanges = True
does actually do the oposite of what you think:
savechanges = True because of the missing := sees savechanges as an undeclared variable of type Variant and compares if this is True. Since it is not declared and not initialized with any value the result of this statement is False.
Finally you submit that result False as first parameter to ActiveWorkbook.Close so it is the same as writing ActiveWorkbook.Close False. So what your code actually does is it closes the workbook without saving changes.
If you used Option Explicit it would have notified you that savechanges is an undeclared variable. This way this fault would have been prevented. Without that notification it is much harder to see and find that issue.
Therefore I recommend always to activate Option Explicit: In the VBA editor go to Tools › Options › Require Variable Declaration.

Copy image from one worksheet (always named "Template") to worksheet with variable names

I need to copy an image from my invoice template worksheet to another worksheet with variable names. For example, the name of the sheet could be "03-000008" or "04-000005" or any other name. This problem would be easy to solve if the sheets had the same name, but since they are variable, I am struggling. Any help would be much appreciated! Thank you in advance!
Tim suggested that I add the code I am working with (thanks Tim!) Here is the code that almost works, but instead of pasting the image to my new, active invoice sheet, it pastes it right on the template itself.
Sub image()
With ActiveSheet
Set i = Sheets("Template")
Set e = ActiveSheet
i.Shapes.Range(Array("Picture 4")).Select
Selection.Copy
e.Range("b1:b4").Select
ActiveSheet.Paste
End With
End Sub
Try this:
Sub image()
Dim ws As Worksheet
ThisWorkbook.Worksheets("Template").Shapes("Picture 4").Copy
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "##-######" Then 'check matches pattern [2digits-6digits]
ws.Paste Destination:=ws.Range("B1")
MsgBox "Pasted to " & ws.Name
Exit For 'no need to check further
End If
Next ws
End Sub
If all you need to do is copy the image from Template to the activesheet then:
Sub CopyLogo()
ThisWorkbook.Worksheets("Template").Shapes("Picture 4").Copy
ActiveSheet.Paste Destination:=ActiveSheet.Range("B1")
End Sub

VBA Macros to insert a row at the end of a table, then paste values of previously copied lines in a specific range of the new row

I'm looking for help on a VBA Macros. This is my current code. Where the **** are I need some code to insert a row at the end of the table on the active worksheet, and then paste the values copied in the above code with the range of ("E1:R8") into the range (E?:R?") of the newly created row.
Sub Workbook()
Dim wb As Workbook
Set wb = Workbooks.Add
ThisWorkbook.Sheets("RFP Form").Copy Before:=wb.Sheets(1)
ThisWorkbook.Sheets("DataHelperSheet").Copy After:=wb.Sheets(1)
Application.DisplayAlerts = False
wb.SaveAs "Z:\Temp\test3.xlsx"
Application.DisplayAlerts = True
ActiveWorkbook.SaveAs FileName:="Z:\Temp\" & Range("I1").Value
Worksheets("DataHelperSheet").Activate
Range("E1:R8").Select
Selection.Copy
Workbooks("Proposal Quote Master List(LB).xlsm").Activate
Worksheets("Master List").Activate
'***
Range("E1:R298").PasteSpecial Paste:=xlPasteValues
End Sub
Don't name your sub Workbook it is a reserved word because VBA uses this for worbook objects (see at Dim wb As Workbook) and this can be very confusing for humans and VBA.
Don't mix ThisWorkbook and ActiveWorkbook and avoid using Activate, ActiveWorkbook and .Select. ThisWorkbook is the workbook the code is written in (it never changes. ActiveWorkbook is the workbook that has focus (is on top) and it can easily change by a single mouse click (therefore it is not a very reliable reference). Instead always try to use a fix reference like you did with wb.SaveAs.
Make sure all your Range objects have a workbook and worksheet specified. If you write Range("I1").Value VBA does not definitely know which workbook or worksheet you mean. It guesses you mean the active ones. But again this is not very reliable because this can change by a single mouse click. Make sure you tell VBA exactly what you mean by using something like wb.Workbooks("Sheet1").Range("I1").Value so there is no room for VBA to start guessing.
Stop using .Select. Instead of
Worksheets("DataHelperSheet").Activate
Range("E1:R8").Select
Selection.Copy
just write
wb.Worksheets("DataHelperSheet").Range("E1:R8").Copy
again specify the workbook wb if working with more than one workbook.
To find the last used cell in column E for example use
wsMasterList.Cells(wsMasterList.Rows.Count, "E").End(xlUp)
and use .Offset(RowOffset:=1) to move one row down to the next empty cell to paste at.
So you end up with something like:
Option Explicit
Public Sub CreateWorkbook()
Dim wb As Workbook
Set wb = Workbooks.Add
ThisWorkbook.Sheets("RFP Form").Copy Before:=wb.Sheets(1)
ThisWorkbook.Sheets("DataHelperSheet").Copy After:=wb.Sheets(1)
Application.DisplayAlerts = False
wb.SaveAs "Z:\Temp\test3.xlsx"
Application.DisplayAlerts = True
wb.SaveAs Filename:="Z:\Temp\" & wb.Workbooks("SPECIFY YOUR SHEET").Range("I1").Value '‹~~ specify sheet name
wb.Worksheets("DataHelperSheet").Range("E1:R8").Copy
Dim wsMasterList As Worksheet
Set wsMasterList = Workbooks("Proposal Quote Master List(LB).xlsm").Worksheets("Master List")
wsMasterList.Cells(wsMasterList.Rows.Count, "E").End(xlUp).Offset(RowOffset:=1).PasteSpecial Paste:=xlPasteValues
End Sub
You can find the last row in a table by using this after you've selected the first cell in the table: (Try it like this)
Range("E1").Columns.End(xlDown).Offset(1,0).EntireRow.Insert
Or you can paste the data with:
.PasteSpecial Paste:=xlPasteFormats
You should look at ExcelCampus and this stack overflow question How to insert copied cells instead of paste
Above should give you all you need to do what you are asking for.

Issue with VBA script running between .xlsm and .xlsb formats

Problem:
Because the .xlsb (herein referred to as TheirFile.xlsb) is downloaded from a third party twice a week, the VBA script must be held by the .xlsm (MyFile.xlsm).
The process is simple:
Focus TheirFile.xlsb
Apply some filters on the data (headers at row 3)
Select the cell AW2 and copy the value (it contains a formula, this may be where the issue occurs)
Focus MyFile.xlsm
Select the cell J28 and paste with ...pastespecial xlPasteAll
However upon checking the code and hitting run, I get nothing in the cell.
Attempts:
Most of them are almost identical, and with the way I (attempt to) bug fix I honestly don't recall all of them.
I used variations on
Workbooks("TheirFile.xlsb").Activate
Range("AW2").Copy
to copy it without error, and
Workbooks("MyFile.xlsm").Activate
Range("j28").Select
ActiveCell.PasteSpecial xlPasteAll
to paste. Something here is failing without returning an error.
I have tried several ways of copying, even a clunky
Range("AW2").Select
x = Selection.Value
Workbooks("MyFile.xlsm").Activate
Range("j28").Select
Selection.Value = x
Which of course didn't work.
Current code and additional info:
Currently I have this in place
Option Explicit
Sub MyMacro() 'indentations for readability
Workbooks("TheirFile.xlsb").Activate
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
'various filters
Dim x As Integer
Workbooks("TheirFile.xlsb").Activate
Range("AW2").Copy
Workbooks("MyFile.xlsm").Activate
Range("j28").Select
ActiveCell.PasteSpecial xlPasteAll
End Sub
The cell AW2 has a =SUBTOTAL(9,cell:cell) formula in it.
The cell j28 is a merged cell.
Questions:
Is there a quick fix for my code?
Would it be more effective to simply perform the subtotal again inside of VBA to avoid the issue?
FIXED
sheets("sheet1").range("AW2").copy
workbooks("MyFile.xlsm").activate
Range("j28").select
activecell.pastespecial xlPasteValues
range("").select appears not to work if the range is in a binary workbook but the macro is in a macro-enabled workbook.
You can/should avoid any uneccessary select/active (also copy/paste is not needed to just transfer values)
Option Explicit
Sub MyMacro()
Dim wsSrc as worksheet
Set wsSrc = workbooks("TheirFile.xlsb").worksheets(1) 'or ws name etc
If wsSrc.FilterMode Then
wsSrc.ShowAllData
End If
'various filters 'USE wsSrc not activesheet
'ThisWorkbook is the wb where your code is running...
ThisWorkbook.worksheets("sheetNameHere").range("J28").value = _
wsSrc.range("AW2").value
End Sub

ThisWorkbook.SaveAs Filename doesn't save and no error code (that I see)

I'm a newbie. I have code that I inherited that copies worksheets from a monthly workbook into a new workbook and creates a summary sheet. It works for April data, but for May and later months' data when it gets to the save it spins a bit and then just dies with no error code. I can't figure out what must be different between the monthly worksheets that could be making this die. I've run in immediate mode and I'm still not seeing any indication of the problem. Any suggestion on how to track down the problem would be greatly appreciated.
Set wb2 = ActiveWorkbook
wb2.Activate
Sheets("977-053").Select 'Add sheets
ActiveSheet.Shapes.Range(Array("Picture 4")).Select
Cells.Select
Selection.Copy
Windows("RH ARAP Summary BASIC.xlsm").Activate
Sheets("Chavez").Select
Cells.Select
ActiveSheet.Paste
wb2.Activate
Sheets("977-05J").Select
Application.CutCopyMode = False
Selection.Copy
Windows("RH ARAP Summary BASIC.xlsm").Activate
Sheets("Pangburn").Select
ActiveSheet.Paste
wb2.Activate
Sheets("977-05K").Select
Application.CutCopyMode = False
Selection.Copy
Windows("RH ARAP Summary BASIC.xlsm").Activate
Sheets("Geier").Select
ActiveSheet.Paste
wb2.Activate
Sheets("977-05R").Select
Application.CutCopyMode = False
Selection.Copy
Windows("RH ARAP Summary BASIC.xlsm").Activate
Sheets("Martin").Select
ActiveSheet.Paste
wb2.Close SaveChanges:=False 'close opened TO 5
MsgBox "ready to Save"
Sheets("RH ARAP Summary").Select 'save ARAP to division folder to send
ThisWorkbook.SaveAs Filename:="May-2"
Your code was largely generated by the macro recorder. What it's doing is quite simple, but it is difficult to work with in this form. If you change it so that variables are defined, it will be much cleaner and easier to work with.
To get you started, here is a simple bit of code that does something similar, with variables properly defined. The animated .gif shows it working to copy the contents from a sheet in one workbook to a sheet in another (click for detail). Hopefully after studying it you can adjust to solve your problem.
Option Explicit
Sub test()
Dim wb As Workbook, wb2 As Workbook
Dim sh As Worksheet, sh2 As Worksheet
Dim r2 As Range
Set wb2 = ThisWorkbook
Set sh2 = wb2.Worksheets("977-053")
Set r2 = sh2.Range("A1")
For Each wb In Workbooks
If wb.Name = "Book2" Then
Set sh = wb.Worksheets("Chavez")
sh.Cells.Copy
sh2.Activate
r2.Select
sh2.Paste
End If
Next
End Sub

Resources