Building custom solutions that extend, automate, and integrate Microsoft 365 apps.
Resize table using VBA
Hello,
I currently use the following code in order to copy data to another worksheet.
However, when I eliminate rows on the original worksheet, the range of the table for the second worksheet remains the same when I run the macro.
I was wondering if someone could help me understand which function or code I could use so that the table size on the second worksheet is updated to the size of the range whenever I run the macro the way it is.
Thanks :)
Microsoft 365 and Office | Development | Other
Microsoft 365 and Office | Excel | For business | Windows
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data
1 answer
Sort by: Most helpful
-
AI answer
2024-05-23T17:14:23.51+00:00 To update the table size on the second worksheet to match the size of the range on the original worksheet, you can use the
ListObject.Resizemethod in VBA. This method resizes the table to match the size of the range specified. Here is an example of how you can modify your code to include this method:Sub CopyData() Dim sourceRange As Range Dim targetRange As Range Dim targetTable As ListObject ' Set the source range to copy from Set sourceRange = Worksheets("Sheet1").Range("A1:C10") ' Set the target range to copy to Set targetRange = Worksheets("Sheet2").Range("A1") ' Copy the data from the source range to the target range sourceRange.Copy Destination:=targetRange ' Resize the table on the second worksheet to match the size of the range Set targetTable = Worksheets("Sheet2").ListObjects("Table1") targetTable.Resize targetRange.Resize(sourceRange.Rows.Count, sourceRange.Columns.Count) End SubIn this example, the
ListObject.Resizemethod is used to resize the table named "Table1" on the second worksheet to match the size of the range copied from the first worksheet. ThetargetRange.Resizemethod is used to create a range of the same size as the source range, which is then passed to theListObject.Resizemethod.
References:
- How to delete every other row on an Excel worksheet
- Methods for transferring data to Excel from Visual Basic
AI-generated content may be incorrect. Read our transparency notes for more information.