How to copy one tablerow to another table using listrow? - excel

I'm trying to copy data rows from different tables and usually i would setup a conveluted setup
counting rows and columns and a couple of level deep for loops.
However, it appears the modern way to go is using listrows.
I tried going over the guide always referenced at https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables
However i seem to miss this "sometable.listobject(1).rows = differentable.listrow(1).rows" roughly...
My code
Sub GenerateOverview()
Dim MainWs As Worksheet
Set MainWs = Worksheets("Overview")
Dim mainTbl As ListObject
Set mainTbl = MainWs.ListObjects(1)
' Later add for each sheet ----
Dim ws As Worksheet
Set ws = Worksheets("ABD") ' ABD to be replaced with activesheet.name LATER
Dim tbl As ListObject
Set tbl = ws.ListObjects(1)
Dim TopXRange As Integer
TopXRange = 10 ' to be changed to user defined range
Dim i As Integer
i = 0
For i = 1 To TopXRange
mainTbl.DataBodyRange.Rows(i) = tbl.DataBodyRange.Rows(i)
' THIS only produces empty cells on maintbl and not the content from tbl.
Next i
' end for each sheet ----
End Sub
Any advice?
Working solution for my task..
Sub GenerateOverview()
Dim MainWs As Worksheet
Set MainWs = Worksheets("Overview")
Dim mainTbl As ListObject
Set mainTbl = MainWs.ListObjects(1)
Dim ws As Worksheet
Dim TopXRange As Integer
TopXRange = 10
Dim i As Integer
i = 1
Dim tbl As ListObject
Dim newI
Dim mainRows As Integer
For Each ws In ThisWorkbook.Worksheets
If ws.Name = MainWs.Name Then GoTo skip
Set ws = Worksheets(ws.Name)
Set tbl = ws.ListObjects(1)
mainRows = mainTbl.ListRows.Count
If mainRows = 0 Then mainRows = 1
For i = newI To TopXRange
mainTbl.ListRows.Add (mainRows)
mainTbl.ListRows(mainRows).Range.Value = tbl.ListRows(i + 1).Range.Value
Next i
skip:
Next
End sub

Still not sure I follow. You probably need to insert a row into your second table before transferring. Something like this works:
Sub x()
Dim t1 As ListObject, t2 As ListObject
Set t1 = Sheet1.ListObjects("Table1")
Set t2 = Sheet1.ListObjects("Table2")
t2.ListRows.Add (3) 'insert new row 3 into second table
t2.ListRows(3).Range.Value = t1.ListRows(4).Range.Value 'transfer to new row from first table
End Sub

Related

Add Unique values from a specific range(column) into a listbox

I am trying to add values from a specific range(column) into a listbox. However, the range has blank cells and duplicates that I am trying to get rid of. The following code works (no error msg) and does populate the listbox, but it does not get rid of the duplicates.
Can someone help?
Private Sub UserForm_Initialize()
Dim rang, rang1 As Range
Dim lstrow As Long
Dim list(), ListUniq() As Variant
Dim iRw As Integer
Dim wb As Workbook
Dim ws As Worksheet
Dim x As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets("Paramed Verification Grid")
Set rang = ws.Range("E3").CurrentRegion
lstrow = rang.Rows.Count + 1
Set rang1 = Range("E3:E" & lstrow)
'list = ws.Range("E3:E" & lstrow).SpecialCells(xlCellTypeConstants)
'Resize Array prior to loading data
ReDim list(WorksheetFunction.CountA(rang1))
'Loop through each cell in Range and store value in Array
x = 0
For Each cell In rang1
If cell <> "" Then
list(x) = cell.Value
x = x + 1
End If
Next cell
ListUniq = WorksheetFunction.Unique(list)
ListUniq = WorksheetFunction.Sort(ListUniq)
ProviderListBx.list = ListUniq
End Sub

Populating multiple cells in row from a reference table, depending on single cell value

I am attempting to populate columns D-J of table1, with the values in table2, columns B-H. The values should be based upon the value of column C in table1.
I have the code below, but I believe that is copying the tables as is and not doing a check of the value in column C.
Images:
Sub wps()
Dim rng As Range
Dim strTable As String
Dim strAddress As String
Dim i As Long
With Worksheets("Procedures")
For i = 1 To .ListObjects.Count
strTable = .ListObjects(i).Name
Set rng = .ListObjects(strTable).Range
strAddress = rng.Cells(2, 3).Address
rng.Copy Destination:=Worksheets("Base Data").Range(strAddress)
With Worksheets("Base Data")
.ListObjects(i).Name = "quals"
End With
Next i
End With
End Sub
It looks like a destination.value=source.value situation, using a single Match(). You could wrap this in a loop on your destWS.
Maybe something like (mock-up, untested):
For i = 2 to lastRowDest
dim sourceWS as worksheet
set sourceWS = sheets(1)
dim destWS as worksheet
set destWS = sheets(2)
destinationSearchTerm = destWS.Cells(i,"C").Value
dim sourceRow as long
sourceRow = Application.Match(destinationSearchTerm, sourceWS.Columns("A"), 0)
destWS.Range(destWS.Cells(i,"D"), destWS.Cells(i,"J") = sourceWS.Range(sourceWS.Cells(sourceRow,"B"),sourceWS.Cells(sourceRow,"H")
Next i

VBA Sub to add row from one table to check multiple tables of line items for qty > 0 and then dynamically add to new table

I'm have various tables stacked on top of each other forming various product offerings to sell. Within each table are offerings related to that group (think grocery and Produce might be the title of the table and then below that lettuce, tomatoes, cabbage, etc as headers with one header being qty - the first column). I want to iterate through each table and for each table that has a qty > 0 print the title of the table and only rows that have a qty>0.
My thought below was to iterate through each table (starting with table1) and if the qty>0, then copy that row into a dynamically created table, add the rows then mark a global flag as true. If true then paste the title, headers, then the created table. I don't know how to add rows to the table though....
Sub CopyRows()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws, ws2 As Worksheet
Set ws = wb.Sheets("Summary")
Set ws2 = wb.Sheets("Sales Ops Ready - Rob")
Dim checkFlag As Boolean
Dim lo As ListObject
Dim globalRowCount As Long
Dim objTable As ListObject
Set objTable = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
Set lo = ws.ListObjects("Table1")
For rw = 1 To lo.Range.Rows.Count
If lo.DataBodyRange(rw, 1) > 0 Then
checkFlag = True
??
End If
Next
End Sub
Here is a rough idea of how it can be done without knowing your exact requirements.
Sub test()
Dim rw As ListRow
Dim newRow As ListRow
Dim lo As ListObject
Dim objTable As ListObject
Set objTable = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
For Each rw In lo.ListRows
If rw.Range(1) > 0 Then 'set the column index here
Set newRow = objTable.ListRows.Add
With newRow
.Range(1) = rw.Range(1)
.Range(2) = rw.Range(2)
'... ... etc
End With
End If
Next rw
End Sub

Loop through Excel Sheet

I'm working with two workbooks. In the first I search for the value in the cell to the right of "Charge Number". Take that value and search the second workbooks pivot table for the matching row, copy it and go back to first work book and paste the data. This works great once. But I'm unable to get a loop to look for the next instance of "Charge Number" and repeat the process. The loop I have in the code isn't right because it finds the first value fine but then searches every next row for the same Charge Number.
Sub FindChargeNo()
Dim Loc As Range
Dim ChgNum As String
Dim SrchRng2 As String
Dim pvt As PivotTable
Dim wb As Workbook, ws As Worksheet
Dim FstWB As Workbook
Dim SecWB As Workbook
Dim rng As Range
Set FstWB = Workbooks("First.xlsm")
Set SecWB = Workbooks("Second_test.xlsx")
Set ws1 = FstWB.Worksheets("New Development")
Set ws = SecWB.Worksheets("Aug 18 Report")
Set pvt = ws.PivotTables(1)
lastRow = FstWB.Worksheets("New Development").Range("J" & Rows.Count).End(xlUp).Row
For i = 1 To lastRow
Set Loc = ws1.Cells.Find(What:="Charge Number")
If Not Loc Is Nothing Then
ChgNum = Loc.Offset(0, 1).Value
Debug.Print ChgNum
Debug.Print SrchRng
With pvt.PivotFields("Project WBS").PivotItems(ChgNum).LabelRange
Set rng = ws.Range(.Resize(.Rows.Count, pvt.TableRange1.Columns.Count).Address)
ws.Range(rng.Address).Copy
End With
SrchRng2 = Loc.Offset(0, 5).Address
FstWB.Worksheets("New Development").Range(SrchRng2).PasteSpecial
Set Loc = ws1.Cells.FindNext(Loc)
Loop While Loc.Address <> firstAddress
End If
Next
End Sub

VBA dynamic row lookup while looping

I'm very new to VBA and should probably spend some time on debugging and learning the formalities of how code should be written.
I am using a loop that uses the Hlookup function to populate a table from on one sheet from data on a master sheet. (This is in the Sub SetMatrix). Within the Sub that performs this task I use some other UDF's, one which copies and pastes the variables (names from a 3rd sheet which may change) I want to lookup from the master sheet.
In any case it runs perfectly fine when the I use a hardcoded number for the row in the lookup function. However, once I try to use a variable (jpmRow instead of a number like 50) for the row it will work the first time only. Then when I run it again I get RunTime error 91 - object variable or withblock variable not set. The debugger take me back to the DynamicRange UDF, Set StartCell line, which confuses me because that is not where I am setting the row variable. Meanwhile if I use a constant for the row it lets me rerun the sub with success every time.
Here is the code:
Option Explicit
Dim wsTemplate As Worksheet
Dim ws As Worksheet
Dim TxtCell As Range
Dim PortfolioCell As String
Dim StartCell As Range
Dim EndCell As Range
Dim RangeParameter As Range
Dim jpmRow As Integer
Dim myColumn As Integer
Dim myRow As Integer
Function DynamicRange(TxtToFind As String) As Range
Dim k As Integer
k = iCount
Set ws = Sheets("Template")
Set StartCell = ws.Cells.Find(TxtToFind).Offset(2, 0)
myColumn = StartCell.Column
myRow = StartCell.Row
Set EndCell = ws.Cells(myRow + k - 1, myColumn)
Set DynamicRange = ws.Range(StartCell.Address, EndCell.Address)
'Set DynamicRange = RangeParameter
End Function
Function iCount() As Integer
Set ws = Sheets("Template")
Set StartCell = ws.Cells.Find("Ticker").Offset(2, 0)
Set EndCell = ws.Cells.Find("Total").Offset(-1, 0)
iCount = ws.Range(StartCell.Address, EndCell.Address).Rows.Count
End Function
Sub SetMatrix()
Dim StartTable As Range
Dim iRows As Range
Dim iColumns As Range
Dim myArray(50, 50) As Integer
Dim wsJPM As Worksheet
Dim i As Integer
Dim j As Integer
Set StartTable = Sheets("Correlation Matrix").Range("A3")
Set iRows = Range(StartTable.Offset(1, 0).Address, StartTable.Offset(iCount, 0).Address)
Set iColumns = Range(StartTable.Offset(0, 1).Address, StartTable.Offset(0, iCount).Address)
Set wsJPM = Sheets("JPM")
Sheets("Correlation Matrix").Cells.ClearContents
Sheets("Correlation Matrix").Cells.ClearFormats
DynamicRange("Asset Class").Copy iRows
DynamicRange("Asset Class").Copy
iColumns.PasteSpecial Transpose:=True
For i = 1 To iCount
For j = 1 To iCount
jpmRow = wsJPM.Cells.Find(StartTable.Offset(i, 0), SearchOrder:=xlColumns, LookAt:=xlWhole).Row
StartTable.Offset(i, j).Value = Application.WorksheetFunction.HLookup(StartTable.Offset(0, j), Sheets("JPM").Range("B1:BZ100"), jpmRow, False)
Next j
Next i
End Sub

Resources