'How to create a new table out of pasted values VBA
I try to make a table out of new range which has just been pasted (it is an extraction of old table but only part of it, not entire so it doesn't paste as a table) in the worksheet, however I got an error. It used to even create a table with this error 5 - invalid procedure or call
Set RngTable = ThisWorkbook.Worksheets("Sheet1").Range("A1:D5")
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set DestRange = Cells(LastRow + 3, "A")
RngTable.Copy
DestRange.PasteSpecial xlPasteAll
DestRange.CurrentRegion.Select
Set newtbl = ActiveWorkbook.Sheets("Sheet1").ListObjects.Add(xlSrcRange, DestRange.CurrentRegion.Select, , xlYes)
Solution 1:[1]
Copy Range to a New Table
One Worksheet
Option Explicit
Sub CopyToNewTable()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim srg As Range: Set srg = ws.Range("A1:D5")
Dim slCell As Range: Set slCell = ws.Cells(ws.Rows.Count, "A").End(xlUp)
Dim dfCell As Range: Set dfCell = slCell.Offset(3)
' Resize to the size of the source.
Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
srg.Copy drg
' ... or if only values is an option, more efficient is:
'drg.Value = srg.Value
Dim dtbl As ListObject
Set dtbl = ws.ListObjects.Add(xlSrcRange, drg, , xlYes)
End Sub
Two Worksheets
Sub CopyToNewTable2Worksheets()
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets("Sheet1")
Dim srg As Range: Set srg = sws.Range("A1:D5")
Dim dws As Worksheet: Set dws = ThisWorkbook.Worksheets("Sheet2")
Dim dfCell As Range
Set dfCell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(3)
' Resize to the size of the source.
Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
srg.Copy drg
Dim dtbl As ListObject
Set dtbl = dws.ListObjects.Add(xlSrcRange, drg, , xlYes)
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
