Pasting after ClearContents in VBA - excel

I am trying to copy data from a table into another sheet.
Sub ListOfSquads()
Sheets("Apontamentos").Select
Range("Apontamentos[[#Headers],[Área]]").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ThisWorkbook.Sheets("Squads").Select
ThisWorkbook.Sheets("Squads").Columns("A:A").ClearContents
ThisWorkbook.Sheets("Squads").Range("A1").Select
ThisWorkbook.Sheets("Squads").Paste
Application.CutCopyMode = False
End Sub
The ClearContents command is making a
Run-Time error '1004'> Application-defined or object-defined error.

Copy Excel Table Column (ListColumn.Range)
In your code, when you did the ClearContents, you actually removed the copied range from the clipboard. As Tim Williams suggested in the comments, you had to move the ClearContents line before the Selection.Copy line and appropriately rearrange the Select lines.
Using Select is a Macro Recorder 'thing' and is best avoided in your code, as described
in this legendary post.
This code uses the Range.Copy method.
Option Explicit
Sub ListOfSquads()
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Source
Dim sws As Worksheet: Set sws = wb.Worksheets("Apontamentos")
Dim stbl As ListObject: Set stbl = sws.ListObjects("Apontamentos")
Dim slcl As ListColumn: Set slcl = stbl.ListColumns("Área")
Dim scrg As Range: Set scrg = slcl.Range
' Destination
Dim dws As Worksheet: Set dws = wb.Worksheets("Squads")
dws.Columns("A").ClearContents
Dim dfCell As Range: Set dfCell = dws.Range("A1")
' Copy
scrg.Copy dfCell
End Sub

Related

VBA Copy/Paste Into Another Workbook and Offset

I'm trying to copy and paste a variable range from "Sheet 1" into "Sheet 2" and offset the cell that I'm pasting into Sheet 2 by one row. I'm doing this so I can add more data into Sheet 2 without overwriting data already pasted.
I created the desired copying ranges for sheet 1:
Dim rw As Range
Set rw = Sheets("Sheet 1").Range(Range("A4"), Range("A4").End(xlDown))
Dim clm As Range
Set clm = Sheets("Sheet 1").Range(Range("A4"), Range("A4").End(xlToRight))
Now I want to paste the range into Column A from Sheet 2 but under the last row used.
I got the following code to work to paste into cell A3 of Sheet 2:
Sheets("Sheet 1").Range(rw, clm).Copy Sheets("Sheet 2").Range("A3")
But I don't know how to offset by 1 row under every time.
Any help would be appreciated!
Copy Data From Table
A Quick Fix
Sub CopyData()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets("Sheet1")
Dim srg As Range
With sws.Range("A4")
Set srg = sws.Range(.End(xlDown), .End(xlToRight))
End With
Dim dws As Worksheet: Set dws = wb.Worksheets("Sheet2")
Dim dfCell As Range
Set dfCell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
srg.Copy dfCell
End Sub

VBA Copy Cells vs Rows

I don't use VBA much at all. I found some code online that has me moving in the right direction, however, I'm struggling how to copy just the values in column "A" rather than copying all the rows. The bold/italic area is where I believe the problem lies.
`For i = 2 To a
If Sheets(Range("O1").Value).Cells(i, 9).Value = "False" Then
***Sheets(Range("O1").Value).Rows(i).Copy***
Worksheets("Product_Lookup").Activate
B = Worksheets("Product_Lookup").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Product_Lookup").Cells(B + 1, 1).Select
ActiveSheet.Paste
Worksheets("Product_Lookup").Activate`
Using Variables
By using variables, your code will become more readable (understandable).
Activating and selecting often leads to mistakes and it severely slows down the operation. Avoiding this is
illustrated in this post.
The following illustrates the Workbook-Worksheet-Range hierarchy.
' The usual approach is e.g.:
'Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
'Dim iws As Worksheet: Set iws = wb.Worksheets("Sheet1")
' Note that 'iws' could actually be 'dws', we don't know!
Dim iws As Worksheet: Set iws = ActiveSheet ' unknown worksheet?
Dim wb As Workbook: Set wb = iws.Parent
Dim sws As Worksheet
On Error Resume Next ' check if the worksheet exists
Set sws = wb.Worksheets(CStr(iws.Range("O1").Value)) ' it may be empty!
On Error GoTo 0
If sws Is Nothing Then Exit Sub ' the worksheet doesn't exist
Dim dws As Worksheet: Set dws = wb.Worksheets("Product_Lookup")
Dim dCell As Range
Set dCell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
For i = 2 To a
If CStr(sws.Cells(i, "I").Value) = "False" Then
sws.Cells(i, "A").Copy dCell
' If you only need values then the following is more efficient:
'dCell.Value = sws.Cells(i, "A").Value
Set dCell = dCell.Offset(1)
End If
Next i

Copying data from one Worksheet to another

I have code where I process and eliminate Mass Spectrometry data (which works).
I have another command to copy that data from its worksheet and to paste it to the same sheet with the Macro (Sheet1). It pastes a line of code to the worksheet instead of the information in proteinGroups.
Set wb = Workbooks.Open("C:\Users\X241066\Downloads\PGroupTest.xlsm")
myFile = "C:\Users\X241066\Desktop\Pgroup\proteinGroups.xls"
Workbooks.Open myFile
Worksheets("proteinGroups").Copy
Workbooks("ProteinGroups.xls").Close SaveChanges:=True
wb.Activate
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("E1")
Application.CutCopyMode = False
Every iteration of commands I tried pastes the data to a new random workbook.
Copy the UsedRange to Another Workbook
Worksheet.UsedRange property
Range.Copy method
On the Worksheet.Copy method page, the following is stated:
If you don't specify either Before or After, Microsoft Excel creates a new workbook that contains the copied Worksheet object.
Option Explicit
Sub CopyProteinGroups()
' Source (Copy FROM (Read))
Dim swb As Workbook
Set swb = Workbooks.Open("C:\Users\X241066\Desktop\Pgroup\proteinGroups.xls")
Dim sws As Worksheet: Set sws = swb.Worksheets("ProteinGroups")
Dim srg As Range: Set srg = sws.UsedRange
' Destination (Copy TO (Write))
Dim dwb As Workbook
Set dwb = Workbooks.Open("C:\Users\X241066\Downloads\PGroupTest.xlsm")
Dim dws As Worksheet: Set dws = dwb.Worksheets("Sheet1")
Dim dfCell As Range: Set dfCell = dws.Range("E1")
' Copy
srg.Copy dfCell
' Save and/or Close
swb.Close SaveChanges:=False ' no need to save; it was only read from
' dwb.Close SaveChanges:=True ' save when you're done; it was written to
End Sub

I would like to loop copy paste data from One Workbook to Another Workbook's sheets with same names?

So I have some Workbooks (2020 & 2021).
Each have 12 Sheets which are based on Month Name eg Jan, Feb, March.
So I would like to write a code to paste data from Sheet("Jan") to Sheet("Jan") and so on from the Workbook 2020 to Workbook 2021 in simple codes.
To do so I have written 25 Codes 12 to Copy and 12 to paste and one Master code to Run all of them.
Is there better alternative to Copy paste them by shortest easiest possible code.
Can I do it with loop. Match Sheets Name and Paste from One Workbook to Another.
Below is example of Code I have written.
Sub Master_Code()
Call_Jan_Copy
Call_Feb_Copy
Call_Mar_Copy
Call_Apr_Copy
Call_May_Copy
Call_Jun_Copy
Call_Jul_Copy
Call_Aug_Copy
Call_Sep_Copy
Call_Oct_Copy
Call_Nov_Copy
Call_Dec_Copy
End Sub
Sub Jan_Copy()'Code-1
Sheets("Jan").Select
ActiveSheet.Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Call Jan_Paste
End Sub
Sub Jan_Paste()'Code-2
Sheets("Jan").Select
ActiveSheet.Range("A1").Select
ActiveSheet.Range("A1048576").End(xlUp).Offset(1, 0).Select
ActiveCell.PasteSpecial xlPasteAll
Application.CutCopyMode = False
End Sub'
Append Worksheet Data
Option Explicit
Sub AppendLastYear()
Const sFilePath As String = "C:\Test\2020.xlsm"
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)
Application.ScreenUpdating = False
Dim sws As Worksheet
Dim srg As Range
Dim dws As Worksheet
Dim dfCell As Range
For Each dws In dwb.Worksheets
Set dfCell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
Set sws = swb.Worksheets(dws.Name)
With sws.Range("A1").CurrentRegion
Set srg = .Resize(.Rows.Count - 1).Offset(1)
End With
srg.Copy dfCell
Next dws
swb.Close SaveChanges:=False
Application.ScreenUpdating = True
MsgBox "Last year appended.", vbInformation
End Sub
Don't rely on ActiveSheet or ActiveWorkbook. Use references instead
Something like
Sub CopyMonths()
Dim wbSrc As Workbook
Dim wbDst As Workbook
Dim wsSrc As Worksheet
Dim wsDst As Worksheet
Set wbSrc = Application.Workbooks("NameOfYourSourceBook.xlsx/m/b") ' Update to your book name, including extension
Set wbDst = Application.Workbooks("NameOfYourDestinationBook.xlsx/m/b") ' Update to your book name, including extension
For Each wsSrc In wbSrc.Worksheets
Set wsDst = wbDst.Worksheets(wsSrc.Name)
wsSrc.UsedRange.Copy
wsDst.Cells(1, 1).PasteSpecial xlPasteAll
Next
End Sub
You might want to consider what to do if
Source wb has more sheets (test for some distinguishing feature before copying)
Dest wb is missing one of the sheets (test for existing, create if missing)
There is existing data on some dest sheets (clear sheet, or paste below)

Copy non-contiguous selection from workbook to another workbook

I copy data from workbook to another workbook ,copying of single contiguous selection works without problem.
But, If I copied two selections (using CTRL) , even adjacent , nothing copied to the destination workbook (with no error raised).
How to adapt the below code to make it Copy non-contiguous selection from workbook to another?
In advance, grateful for useful answer and comments.
Dim wb As Workbook: Set wb = ThisWorkbook 'Source Workbook
Dim srg As Range: Set srg = wb.ActiveSheet.Range(Selection.Address)
Dim wb1 As Workbook: Set wb1 = Workbooks.Add 'Destination Workbook
Dim drg As Range: Set drg = wb1.Sheets(1).Range("A1")
srg.Copy drg
srg.Copy
drg.PasteSpecial Paste:=xlPasteColumnWidths
Dim r As Range
For Each r In drg.Rows
r.WrapText = True
If r.RowHeight < 40 Then r.RowHeight = 40 'This line works
Next r
This answer refers to #karma
Just I need to copy columns width then copy values after it.
srg.Copy
drg.PasteSpecial Paste:=xlPasteColumnWidths
srg.Copy drg

Resources