Find Match, Copy Row from Sheet1 and Insert Into Sheet2 - excel

In Sheet1, I have around 10,000 rows representing different people. Each person has a unique ID located in column D, which is a number sequence stored as text.
In Sheet2, I have around 1,200 person entries that have have a reference to a matching person in Sheet1 located in column A. This reference is the same unique ID used in Sheet1.
What I would like is to have a macro do is this:
read-in the value of cell A1 on Sheet2
find the matching value in column D on Sheet1
copy the matching row in Sheet1
insert the matching row underneath on Sheet2 (row 2)
insert a blank row (row 3)
repeat the steps for the remaining 9,999 entries on Sheet2 so that the matching data always falls underneath the read-in value, followed by a blank row
Any help would be appreciated.

May I advise that in future you show evidence of trying to solve the problem you are having. That way we know you are participating in the community and not attempting to extract free labour from it.
Here is a solution you can try. It starts from the currently selected cell in sheet2.
Function DoOne(RowIndex As Integer) As Boolean
Dim Key
Dim Target
Dim Success
Success = False
If Not IsEmpty(Cells(RowIndex, 1).Value) Then
Key = Cells(RowIndex, 1).Value
Sheets("Sheet1").Select
Set Target = Columns(4).Find(Key, LookIn:=xlValues)
If Not Target Is Nothing Then
Rows(Target.row).Select
Selection.Copy
Sheets("Sheet2").Select
Rows(RowIndex + 1).Select
Selection.Insert Shift:=xlDown
Rows(RowIndex + 2).Select
Application.CutCopyMode = False
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(RowIndex + 3, 1).Select
Success = True
End If
End If
DoOne = Success
End Function
Sub TheMacro()
Dim RowIndex As Integer
Sheets("Sheet2").Select
RowIndex = Cells.row
While DoOne(RowIndex)
RowIndex = RowIndex + 3
Wend
End Sub

Related

Paste to row based on row number value in cell

I am trying to write a macro that copies data from a form (Contractor Entry Form, range "U5:AT5") and pastes it to a database (CONTRACTOR DATABASE).
When a record is edited, it requests the Employee ID# and finds that row on the database, and pastes that row number reference temporarily into cell Contractor Entry Form "L1".
I need to then paste the copied data to the database on that row number (-1) that is referenced in cell "L1". If there is no value in "L1" that means it is a new entry and should then just paste to the last row -- as opposed to pasting over a previous record row.
Help, please. My code is here--
Sub ContractorEntry
Range("U5:AT5").Copy
Sheets("CONTRACTOR_DATABASE").Select
Dim R As Integer
R = Worksheets("CONTRACTOR ENTRY").Range("L1").value
'note-- if there is a value in CONTRACTOR ENTRY L1>0 then
' (it represents a row number --- paste value to that row -1 onto
' Contractor Database sheet.
If Worksheets("CONTRACTOR ENTRY").Range("L1") > 0 Then
Sheets("CONTRACTOR_DATABASE").Cells (R -1, 1)
Selection.PasteSpecial
End If
Else
'if there is no value in cell L1 then the following to just paste to the next blank row
lMaxRows = Cells(Rows.Count, "A").End(xlUpSelection.PasteSpecial.Row
Range("A" & lMaxRows + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks :=False, Transpose:=False
'This returns to the contractor entry form and clears contents
Sheets("CONTRACTOR ENTRY").Select
Range("D3:M1").Select
Selection.ClearContents
'Should go back to Contractor Entry Form for Name and a new entry in cell D3
Range("D3").Select
End Sub
There's almost never any need to use Select/Activate see here for guidelines on how to improve your code: How to avoid using Select in Excel VBA
Something like this should work:
Sub ContractorEntry()
Dim rw, wsInput As Worksheet, wsDB As Worksheet
'use worksheet varaibles for easier maintenance
Set wsInput = ThisWorkbook.Worksheets("CONTRACTOR ENTRY")
Set wsDB = ThisWorkbook.Worksheets("CONTRACTOR_DATABASE")
rw = wsInput.Range("L1").Value - 1
'if row not present then get next empty row
If rw < 1 Then rw = wsDB.Cells(Rows.Count, "A").End(xlUp).Row + 1
'copy over values directly (no copy/paste)
With wsInput.Range("U5:AT5")
wsDB.Cells(rw, "A").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
With wsInput
.Activate
.Range("D3:M1").ClearContents
.Range("D3").Select
End With
End Sub

Insert sequential number for each row with a record

I'm very new to VBA and learning through code I find on the internet, and also using macros to see code.
I have an imported xls with three columns of data. I have code that does the following:
Inserts a new column A
Deletes column B
Delete rows with no data
Inserts two columns
So far - okay. What I am then trying to do is insert a number starting at 1 in column A1 and sequentially filling in until all rows with records have a number. I used a macro to see the code, but the range will vary (i.e. there are not always 52 rows in my import).
Is there a way to make this dynamic by only applying a number where there is data in the row (Column B will always have data)?
Thanks in advance - all help greatly appreciated!
Sub DeleteBlankRows()
Dim x As Long
Dim lastRow As Long
Dim A As Long
' INSERT A NEW COLUMN A FOR NUMERICAL SEQUENCE
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'DELETE ALL BLANK ROWS
With ActiveSheet
For x = .Cells.SpecialCells(xlCellTypeLastCell).Row To 1 Step -1
If WorksheetFunction.CountA(.Rows(x)) = 0 Then
ActiveSheet.Rows(x).Delete
End If
Next
End With
'add two new columns for population
ActiveCell.Offset(0, 2).Columns("A:A").EntireColumn.Select
Selection.Delete Shift:=xlToLeft
ActiveCell.Columns("A:B").EntireColumn.Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.NumberFormat = "#"
'code to enter a sequential number starting at 1 for every row that has a record
ActiveSheet.Range("A1").Select
ActiveCell.Select
ActiveCell.FormulaR1C1 = "1"
ActiveCell.Select
Selection.AutoFill Destination:=ActiveCell.Range("A1:A52"), Type:= _
xlFillSeries
ActiveCell.Range("A1:A52").Select
ActiveWindow.SmallScroll Down:=15
End Sub
There are a lot of stuff to improve your my code, but this should get you started
Some things to begin:
Use option explicit at the top of your modules so you don't have unexpected behavior with undefined variables
Always indent your code (see www.rubberduckvba.com a free tool that helps you with that)
Try to separate your logic defining variables and the reusing them
Name your variables to something meaningful and easy to unterstand (avoid x or r)
Write the code steps in plain English first, then develop it in VBA
Check the code's comments, and adapt it to fit your needs
Code
Public Sub PrepareFormat()
' Set a target sheet
Dim targetSheet As Worksheet
Set targetSheet = ActiveSheet ' This could be always the same sheet. If so, replace activesheet with thisworkbook.Sheets("NameOfTheSheet")
' Insert a new column for numerical sequence
targetSheet.Columns("A:A").Insert shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
' Delete all blank rows
Dim counter As Long
With targetSheet
For counter = .Cells.SpecialCells(xlCellTypeLastCell).Row To 1 Step -1
If WorksheetFunction.CountA(.Rows(counter)) = 0 Then
.Rows(counter).Delete
End If
Next counter
End With
' Add two new columns for population (this next lines would make column B empty, so filling sequentally would not work below
'targetSheet.Columns("D:D").Delete shift:=xlToLeft
'targetSheet.Columns("A:B").Insert shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'targetSheet.Columns("A:B").CurrentRegion.NumberFormat = "#" -> commented this line because cells are going to be empty. What do you want to format as text? maybe this could go after you add the numbers. Also formatting the whole column is a waste of resources
' Insert a number starting at 1 in column A1 (added number 2 to fill down in sequence)
targetSheet.Range("A1").Value = 1
targetSheet.Range("A2").Value = 2
' Sequentially fill in until all rows with records have a number (this doesn't take into account if there are gaps in column b)
Dim referenceRange As Range
Set referenceRange = targetSheet.Range("B1:B" & targetSheet.Range("B" & targetSheet.Rows.Count).End(xlUp).Row)
targetSheet.Range("A1:A2").AutoFill Destination:=referenceRange.Offset(0, -1)
End Sub
Let me know if it works
PS. Check Sidar's answer on how to properly delete empty rows: https://stackoverflow.com/a/9379968/1521579
Could you try this?
'code to enter a sequential number starting at 1 for every row that has a record
'remove your code from here on and substitute with the following
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
ActiveSheet.Range("A1").Select
With ActiveCell
.FormulaR1C1 = "1"
.AutoFill Destination:=ActiveCell.Range("A1:A" & LastRow), Type:=xlFillSeries
End With

Select last column in the first row which contains text and go to the next row and do the same

can someone please help me on this code which i have been having trouble to do for the past 2 days. What i need to do is find the last column in that specific row starting from Column C and onwards if there's any text which i have managed to find but it only does it for the first row as i can't seem to find the code to go to the next row and repeat the action; the order it should work in is by going to the last cell in that column of that row and go left and when it find text in a cell it will then insert a row below it and cut and paste the text into the below row in column B. This will continue on until all the cells from C and onwards don't contain any text and move on to the next Row repeating the above action.
Sub newcode_eachline()
Dim datacheck as Range
Dim valuecell As String
Dim cell As Range
Range("A1").Select
Do
Set datacheck = Range(ActiveCell.Offset(0, 2), ActiveCell.Offset(0, 2).End(xlToRight))
For Each cell In datacheck
If cell <> "" Then
ActiveCell.Select
valuecell = Cells(Columns.Count).End(xlToLeft).Select
ActiveCell.Offset(1, 0).EntireRow.Insert shift:=xlDown
ActiveCell.Select
Selection.Cut
ActiveCell.Offset(1, 0).End(xlToLeft).Select
ActiveCell.Offset(0, 1).Select
ActiveSheet.Paste
ActiveCell.Offset.End(xlToLeft).End(xlUp).Select
Else
Do
ActiveCell.Offset(1, 0).Select
Loop Until ActiveCell.Offset(0, 0) <> ""
End If
Next
Loop Until ActiveCell.Offset(0, 0).End(xlDown).Value = ""
End Sub
The "Do Set datacheck = Range(ActiveCell.Offset(0, 2), ActiveCell.Offset(0, 2).End(xlToRight))
For Each cell In Datacheck," doesn't seem to work properly and i can't seem to find a solution to check from C and all the way to the last column cell if there's any text in that range and the Valuecell = Cells(Columns.Count).End(xlToLeft).Select which only targets the first row.
Much appreciated if someone can help me out with this and let me know.

Match Columns and if match return specific value

How can I create a VBA code that will match 2 reference numbers in different columns and return data in third column.
The reference numbers are located in column A (Sheet1) and column A (Sheet2)
If a match is found, then the Dept. in Sheet 1, Column C, will be copied into an empty column in Sheet 2 Column B.
The code that I have written so far matches data in both columns but only for specific words.
Private Sub CommandButton1_Click()
a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To a
If Worksheets("Sheet1").Cells(i, 3).Value = "North" Then
Worksheets("Sheet1").Rows(i).Copy
Worksheets("sheet2").Activate
b = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("sheet2").Cells(b + 1, 1).Select
ActiveSheet.Paste
Worksheets("Sheet1").Activate
End If
Next
Application.CutCopyMode = False
ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).Select
End Sub
You don't need VBA for this: Juse use a VLOOKUP
See formula used in Column H

Copy value to multiple worksheets

I have one column of values in the master sheet to copy to multiple sheets in a specific cell. Each cell value is copied to each sheet once and is repeated over 625 times. I have one column of values (A2 to A626) in the master sheet to copy to multiple sheets in a specific cell. A2 is copied to sheet 2, cell R4. This is repeated until A626 is copied to sheet 626, cell R4. The sheet containing the A2 to A626 data is "unique"
I have lifted this code from another site and it did not work to my expectation.
Sub copyPasteData()
Dim strSourceSheet As String
Dim strDestinationSheet As String
Dim lastRow As Long
strSourceSheet = "Unique"
Sheets(strSourceSheet).Visible = True
Sheets(strSourceSheet).Select
Range("A2").Select
Do While ActiveCell.Value <> ""
strDestinationSheet = ActiveCell.Value
Selection.Copy
Sheets(strDestinationSheet).Visible = True
Sheets(strDestinationSheet).Select
lastRow = LastRowInOneColumn("R")
Cells(lastRow + 1, 0).Select
Selection.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Sheets(strSourceSheet).Select
ActiveCell.Offset(0, 2).Select
ActiveCell.Offset(1, 0).Select
Loop
You provided very little details, so I will give you some general tips.
To access (set or get) the value of specific cell from specific sheet you can use following syntax:
Worksheets("sheetName").Cells(row, col).Value (row and col are integers, specifying row and column of a cell), so in order to paste the value to cell B3 from sheet "Sheet2" from cell C4 from sheet "Sheet1" you should write:
Worksheets("Sheet2").Cells(3, 2).Value = Worksheets("Sheet1").Cells(4, 3).Value.
Moreover, you can access sheet using integers (1 - first sheet, etc.) instead of names, this way you can use loops to go through every sheet:
Worksheets(i).Cells(row, col).Value, where i, row, col are integers.
After consulting with OP, the code should look like:
Sub CopyToMultipleSheets()
Dim i As Long
For i = 2 To 626
'cell A2 will be referenced to as Cells(2, 1).Value
'generally Ai cell is Cells(i, 1)
'R4 cell is Cells(4, 18)
Worksheets(i).Cells(4, 18).Value = Worksheets("unique").Cells(i, 1).Value
Next i
End Sub

Resources