Excel: comparing names in two different sheets - excel

I have two excel sheets with about 500 rows each. Worksheet A has a name column E) and worksheet B has two name columns for small and large names(H&I). I want to create a loop that goes through and compares these columns and should it find a match paste this match onto a new worksheet.
Further clarification:
On worksheet B the two name columns are akin to Cigna and Cigna Co for example so they are not always the same name repeated, and on Worksheet A the name may be Cigna, so they are not always exact though. But the name of Worksheet A must match 1 or both names on Worksheet B.

Something like this is an easy loop and record, then see if anything from the first sheet is on the second.
Not sure what your small and large names situation is, so I checked both columns
In you VBA IDE go to the tools menu and selecte references. Select "Microstoft ActiveX data objects 2.8 Library. This will be used for the recordset.
Private Sub CommandButton1_Click()
Dim rs As New ADODB.Recordset
Dim ws As Excel.Worksheet
Dim ws2 As Excel.Worksheet
Dim lRow As Long
Dim lRowOut As Long
Set ws = ActiveWorkbook.Sheets("Sheet1")
ws.Activate
Set ws2 = ActiveWorkbook.Sheets("Sheet3")
'Add fields to your recordset for storing data.
With rs
.Fields.Append "Row", adInteger
.Fields.Append "Name", adChar, 25
.Open
End With
'Loop through and record the name
lRow = 1
Do While lRow <= ws.UsedRange.Rows.count
rs.AddNew
rs.Fields("Row").Value = lRow
rs.Fields("Name").Value = ws.Range("E" & lRow).Value
rs.Update
lRow = lRow + 1
ws.Range("A" & lRow).Activate
Loop
If rs.EOF = False Then
rs.MoveFirst
End If
'Switch to the second worksheet
Set ws = Nothing
Set ws = ActiveWorkbook.Sheets("Sheet2")
ws.Activate
'Loop through and see if anything on this sheet was on the first sheet.
lRow = 1
lRowOut = 1
Do While lRow <= ws.UsedRange.Rows.count
'Check if the column H name was recorded from the first sheet
rs.Filter = ""
rs.Filter = "Name='" & ws.Range("H" & lRow).Value & "'"
If rs.RecordCount = 0 Then
rs.Filter = ""
rs.Filter = "Name='" & ws.Range("I" & lRow).Value & "'"
If rs.RecordCount > 0 Then
'It has a date, delete the current row
ws2.Range("A" & lRowOut).Value = rs.Fields("Name").Value
lRowOut = lRowOut + 1
End If
ElseIf rs.RecordCount > 0 Then
'It has a date, delete the current row
ws2.Range("A" & lRowOut).Value = rs.Fields("Name").Value
lRowOut = lRowOut + 1
End If
lRow = lRow + 1
ws.Range("A" & lRow).Activate
Loop
End Sub
If you want to look for a part of the name as you say in your comment, you can use a like. Change the filter lines to something like this.
rs.Filter = "Name LIKE '%" & ws.Range("I" & lRow).Value & "%'"

Doing this with formulas, instead of VBA, I would stick a formula in A1 of your new workbook like the following. Assuming that your "Worksheet A" is in Book1 on Sheet1 and your H and I columns from "Worksheet B" are Book2 on Sheet1:
=if(countif([Book2]Sheet1!H:I, [Book1]Sheet1!E1)>1, [Book1]Sheet1!A1, "")
This says "If, in my columns H and I in Sheet1 of Book2 there is at last one match on the name from Cell E1 in Sheet1 of Book1, then grab the name from Cell E1 on Sheet1 of Book1"
This will leave a good number of blanks, but at that point you can just filter or sort them out.
If the requirements are more complicated than that, like any match across any of three columns, then you can just add the results of multiple CountIf() formulas and test them for > 1, or do a single Countif() for each column and then union the results, sort/filter, and Bob's your uncle.
If this is going to be something you do often, then it may be worth investing in the VBA route as that will take the little bit of manual work out of it.

Related

Excel copy cut paste data from 1 sheet to another with a status in updated in sheet 2 new column

I am new to macro I have created a macro that copies data from excel sheet1 column A & B and paste it in sheet 2 with status as updates in column c. However, it is not working properly it executes with incorrect/incomplete way like for some values in sheet 2 column B it shows updated in column c but for some, it does not... Please help me below is my code.
Secondly, I have coded first for copy paste data from sheet1 to sheet2 there I have specified the range A2:A9999 and B2:B9999 I am not able to simplify it. I mean it should take the entire column A and B than the specified range. Please help me with these 2 parts.............
Sub CopyData()
Dim i As Long
Dim wt As Excel.Worksheet
Set wr = Worksheets("Sheet2")
'Copies and cuts the data from sheet1(TIS) and paste the same in sheet2
With Worksheets("SampleFile")
.Range("A2:A9999").Copy wr.Range("A2") 'Copy
.Range("A2:A9999").Cut wr.Range("A2") 'Cut
.Range("B2:B9999").Copy wr.Range("B2") 'Copy
.Range("B2:B9999").Cut wr.Range("B2") 'Cut
End With
For i = 1 To wr.Cells(wr.Rows.Count, "B").End(xlUp).Row
If wr.Range("B" & i).Value = "FXV" Then
wr.Range("C" & i).Value = "Updated"
ElseIf wr.Range("B" & i).Value = "FST" Then
wr.Range("C" & i).Value = "Updated"
ElseIf wr.Range("B" & i).Value = "FLB" Then
wr.Range("C" & i).Value = "Updated"
ElseIf wr.Range("B" & i).Value = "FFH" Then
wr.Range("C" & i).Value = "Updated"
ElseIf wr.Range("B" & i).Value = "FFJ" Then
wr.Range("C" & i).Value = "Updated"
End If
Next i
End Sub
This code should cut data from A2 to B and LastRow in worksheet SampleFile and paste it to Range A2 in worksheet Sheet2. Then it will loop through all the rows in Sheet2 looking for the value in column B, if it matches the Select Cases will input Updated in column C:
Option Explicit
Sub CopyData()
Dim wr As Worksheet: Set wr = Worksheets("Sheet2")
'Copies and cuts the data from sheet1(TIS) and paste the same in sheet2
'there is no need to copy if you are going to cut
'also use a defined range to copy instead 9999 rows
With ThisWorkbook.Worksheets("SampleFile")
Dim LastRow As Long: LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
'you can also cut both columns at once
.Range("A2:B" & LastRow).Cut wr.Range("A2") 'Cut
End With
Dim i As Long
With wr
For i = 1 To .Cells(.Rows.Count, "B").End(xlUp).Row
'in this case is way shorter to code using the Select statement
'you could also use If x = y or x = z or x = a but Select looks cleaner.
.Cells(i, "B") = Trim(.Cells(i, "B"))
Select Case .Range("B" & i)
Case "FXV", "FST", "FLB", "FFH", "FFJ"
.Range("C" & i) = "Updated"
End Select
Next i
End With
End Sub

Find the total of the same column from multiple sheets and express totals next to sheet name on new sheet

I'm looking to create a macro that will display the Sum from a set column of each of multiple sheets. I need the total of column "K" to be shown 1 row from the last entry of a variable number of entries. It is a requirment that this is in VBA as it needs to run with a number of other functions.
I've tried the below code but it does not give the expected result and seems to be drawing data from other sheets.
Sub SumWorksheets()
Dim LastRow As Long
Dim ws As Worksheet
For Each ws In Worksheets
LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
ws.Range("K" & LastRow + 1) = Application.WorksheetFunction.Sum(Range("K2:K" & ws.Rows.Count))
Next
End Sub
I want the Total of all numbers in Column "K" to display 2 rows below the last number in Row "K"
Declared and fully use ws and LastRow variables. Not using can cause code to pull values from another worksheet. Per comment from #LoveCoding, using a different column as the LastRow can overwrite a cell in Col K. You should have used the LastRow variable, in the Sum function.
Dim ws As Worksheet, LastRow As Long
For Each ws In ThisWorkbook.Worksheets
LastRow = ws.Range("K" & ws.Rows.Count).End(xlUp).Row
ws.Range("K" & LastRow + 1) = Application.WorksheetFunction.Sum(ws.Range("K2:K" & LastRow))
Next

Finding & filling in other Excel sheets based on criteria using VBA

I have a workbook with four worksheets: Overview, apple, banana and pear.
In the sheet overview I have a 3x3 table:
In Out Extra
apple
banana
pear
Cell H5 in Overview contains a date of 2019, which can be selected via a drop-down menu
In each of the apple/banana/pear sheets, I have a 365x3 table:
In Out Extra
1-1-2019
2-1-2019
3-1-2019
.
.
.
31-12-2019
I would like to run a macro so that the In, Out and Extra values from the Overview sheet are filled in the correct worksheet and behind the correct date in that worksheet.
The goal would be that people fill in the overview sheet (In, Out and Extra values as well as a date), they run the macro, and data is automatically stored in the right cell in the right worksheet.
This is a relatively easy example, the actual workbook for which I need this macro has more that 70 "fruits".
I know the code below doesn't work, but I'll hope to show my way of thinking
Sub export()
Dim ws As Worksheet 'worksheet
Dim currentdate As Date 'datum
Dim fruit As String 'Fruit
Worksheets("Overview").Activate 'activate worksheet Overview
currentdate = ActiveSheet.Cells(H5) 'select date value
fruit = Overview.Range(“C6, C8”) 'select range of the fruits
For Each ws In Worksheets 'loop over every worksheet except the Overview sheet
If ws.Name = fruit Then 'crossreference name worksheet with fruit in Overview sheet
ws.Activate 'activating the selected worksheet
If ws.Range("A1:A365") = currentdate Then 'looking for the correct date in the selcted worksheet
fruit = ws.Name
Next ws
End Sub
Vba solution for this:
For this solution to work properly, you should make the sheets APPLE, BANANA and PEAR share same structure. In my example, all this 3 sheets have in column A the date, column B is IN, column C is OUT and column D is EXTRA
Also, in OVERVIEW sheet, make sure the terms APPLE, BANANA and PEAR are exactly equal to names of each sheet (this means no extra spaces, blanks or different chars).
And OVERVIEW must be the active sheet.
My button IMPORT is linked to this code to import data. I want to import data from 17/05/2019 (the yellow rows)
Sub IMPORT_DATA()
Application.ScreenUpdating = False
Range("B2:D4").Clear
Dim i As Long
Dim TargetRow As Long
Dim TargetSheet As String
Dim TargetDate As Date
TargetDate = Range("B6").Value
For i = 2 To Range("A" & Rows.Count).End(xlUp).Row Step 1 'i=2 because dats in OVERVIEW stars at row 2, and Column A
TargetSheet = Range("A" & i).Value
'first, we make sure the date from B6 exists in the target worksheet counting
With Application.WorksheetFunction
If .CountIf(ThisWorkbook.Worksheets(TargetSheet).Range("A:A"), TargetDate) > 0 Then
TargetRow = .Match(CDbl(TargetDate), ThisWorkbook.Worksheets(TargetSheet).Range("A:A"), 0)
Range("B" & i).Value = ThisWorkbook.Worksheets(TargetSheet).Range("B" & TargetRow).Value 'IN value
Range("C" & i).Value = ThisWorkbook.Worksheets(TargetSheet).Range("C" & TargetRow).Value 'IN value
Range("D" & i).Value = ThisWorkbook.Worksheets(TargetSheet).Range("D" & TargetRow).Value 'IN value
End If
End With
Next i
Application.ScreenUpdating = True
End sub
And after executing this code I get in OVERVIEW:
Now I want to export some values to data, and I use this code:
Sub EXPORT_DATA()
Application.ScreenUpdating = False
Dim i As Long
Dim TargetRow As Long
Dim TargetSheet As String
Dim TargetDate As Date
TargetDate = Range("B6").Value
For i = 2 To Range("A" & Rows.Count).End(xlUp).Row Step 1 'i=2 because dats in OVERVIEW stars at row 2, and Column A
TargetSheet = Range("A" & i).Value
'first, we make sure the date from B6 exists in the target worksheet counting
With Application.WorksheetFunction
If .CountIf(ThisWorkbook.Worksheets(TargetSheet).Range("A:A"), TargetDate) > 0 Then
TargetRow = .Match(CDbl(TargetDate), ThisWorkbook.Worksheets(TargetSheet).Range("A:A"), 0)
ThisWorkbook.Worksheets(TargetSheet).Range("B" & TargetRow).Value = Range("B" & i).Value 'IN value
ThisWorkbook.Worksheets(TargetSheet).Range("C" & TargetRow).Value = Range("C" & i).Value 'OUT value
ThisWorkbook.Worksheets(TargetSheet).Range("D" & TargetRow).Value = Range("D" & i).Value 'EXTRA value
End If
End With
Next i
MsgBox "data exported"
Application.ScreenUpdating = True
End Sub
And after executing code, check new data (yellow rows):
Hope this helps a litte bit and you can adapt to your needs.

Search words in two columns and copy to another sheet

In my problem:
First, I need to find "Unit Name" in Column B.
If it found "Unit Name" it should look for "First Name:" in Column D and copy 5 cell right. ("Obama" in I10)
Paste the name "Obama" to Unit Name sheet. (Paste "Obama" to Sheet "1" A1)
I am new in coding therefore i don't know too much about it. I tried with some codes but it is not efficient.
Here is an image to show my problem.
Sub Test()
Dim i As Integer
Dim m As Integer
Dim n As Integer
Dim z As Integer
For i = 1000 To 1 Step -1
If Range("B" & i).Value = "Unit Name" Then
m = 2
m = i + 1
n = i - 18
If Range("D" & n).Value = "First Name:" Then
m = Range("B" & m).Value + 1
Range("H" & n).Copy
Sheets(m).Range("B7").PasteSpecial xlPasteValues
End If
End If
Next i
End Sub
You don't need all those integer variables, you can use a few Range variables instead:
Sub find_name()
Dim mainWS As Worksheet, altWS As Worksheet
Dim unitCel As Range, fNameCell As Range
Set mainWS = Worksheets("Sheet2") 'CHANGE AS NEEDED
Set altWS = Worksheets("Sheet1")
With mainWS
Set unitCel = .Range("B:B").Find(What:="Unit Name")
If Not unitCel Is Nothing Then
Set fNameCell = .Range("D:D").Find(What:="First Name:").Offset(0, 5)
altWS.Range("A1").Value = fNameCell.Value
End If
End With
End Sub
May need to tweak this, depending on where your data is. I am assuming "Obama" could be any text, that is three columns right of column D, where "First Name:" is found.
Sub Shift_Over5()
Dim i As Long
'Sheet name should be a string
Dim SheetName As String
Dim FirstName As Range
Dim UnitName As Range
'Dim l As Byte --> I changed it to lUnitSheetLastrow, because we need to copy the data from sheet1 to sheet 1,2...
' then you need to check the last row of unit sheet and write data to the last row + 1.
Dim lUnitSheetLastrow As Long
Dim FirstMatch As Variant
Dim Start
Start = VBA.Timer
For i = 1 To 40000 Step 1
'For clear code and easy to follow, you need to mention the sheet you want to interact
'Here i use 'Activesheet', i assume that the current sheet is sheet1
If ActiveSheet.Range("A" & i).Value = "Unit Name" Then
' i think we dont need this code line, because we identified the cell in column B has value is "Unit Name"
'Set UnitName = Range("A:A").Find(what:="Unit Name")
' Here you dont need to use Offset
'SheetName = UnitName.Offset(1, 0).Value
SheetName = ActiveSheet.Range("A" & (i + 1)).Value
' Find "First Name" in 20 rows in column E.
' What happen if i<20, the nextline will show the error, because the minimum row is 1
If i < 40 Then
Set FirstName = ActiveSheet.Range("D1" & ":D" & i).Find(what:="First Name:")
Else
Set FirstName = ActiveSheet.Range("D" & i & ":D" & (i + 40)).Find(what:="First Name")
End If
' make sure the SheetName is not empty and Unit sheet is existing in you workbook then copy the first name to unit sheet
If SheetName <> "" And CheckWorkSheetAvailable(SheetName) Then
' Check the first name is not nothing
If Not FirstName Is Nothing Then
'Check if the cell B7 in unit sheet empty or not
If Worksheets(SheetName).Range("H7").Value = "" Then
'if empty, write to B7
Worksheets(SheetName).Range("H7").Value = FirstName.Offset(1, 0).Value
Else
'else, Find the lastrow in column D of unit sheet
lUnitSheetLastrow = Worksheets(SheetName).Cells(Worksheets(SheetName).Rows.Count, 1).End(xlUp).Row
'Write data to lastrow +1
Worksheets(SheetName).Range("A" & (lUnitSheetLastrow + 1)).Value = FirstName.Offset(, 1).Value
End If
End If
End If
'You forgot to put end if here
End If
Next i
Debug.Print Round(Timer - Start, 3)
End Sub
Function CheckWorkSheetAvailable(SheetName As String) As Boolean
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name = SheetName Then
CheckWorkSheetAvailable = True
Exit For
End If
Next
End Function
thank you everyone I found the answer.

VBA Code: Vlookup Sheet1 to copy and paste on Sheet 2 if Sheet 1 contains specific text

Picking your brains here. Trying to do this for days. VBA noob.
Two Sheets: Sourcesheet ("NB & COax PO Detail Test") & Outputsheet ("New build & Coax Test")
Source sheet is an organized list. POs are in Col I and each POs value is broken down by month (J,F til dec). Each row has is dedicated to a unique PO with the monthly forecast broken down by month.
Output Sheet has the POs listed in Rows and Monthly forecast in Columns. The idea is to vlookup the monthly forecast for each PO in source sheet, if the Col C (output sheet) is PO Materials or PO Labor then Vlookup, otherwise skip to next row. Vlookup has to apply the monthly forecast to each month. After each Vlookup I am trying to copy and paste the value so that there isnt too much coding leading to Excel crash. Also in the Source sheet the Col Index Num for the Output Sheet vlookup is listed above each month.
In a nutshell.
If(Or (Outputsheet.Col I ="PO Labor", Outputsheet.Col I ="PO Materials"), Vlookup(Outputsheet.ColE, SourceSheet.Range(Col I to Col AB:5000), SourceSheetR3,False), "") Copy and Paste next Column in the same row repeat until OutputSheet Col R. Copy and paste. Next row.
SourceSheet R3 is variable it changes so I want Vlookup to pick up the Column number from there as stated above each month of the Col.
(Output Sheet & Source Sheet Click the next image) http://imgur.com/SHANSLF&ydjQfb3#0
(Code) http://imgur.com/MieCu5G
Finally finished this with the help of several genereous memebers of this community and Chandoo Community. here is the final code that I put together and that actually works.
Sub MakeFormulas()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Dim X As Long
Dim Z As Long
'What are the names of our worksheets?
Set sourceSheet = Worksheets("Sheet1")
Set outputSheet = Worksheets("Sheet2")
'Determine last row of source
With sourceSheet
SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet
'Determine last row in col C
OutputLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
For y = 17 To 28 'Q to AB
For X = 2 To OutputLastRow
If InStr(1, .Range("C" & X), "PO Materials") + InStr(1, .Range("C" & X), "PO Labor") > 0 And Cells(2, y) = "Forecast" Then
'Apply formula
.Cells(X, y).Value = _
Evaluate("=VLOOKUP($E" & X & ",'" & sourceSheet.Name & "'!$A$2:$L$" & SourceLastRow & ",Match(" & Cells(1, y).Address & ",'" & sourceSheet.Name & "'!$A$1:$AD$1,0),0)")
End If
Next
Next
End With
End Sub

Resources