Reputation: 499
Once again I've got a problem with mixed format data in excel file. I've got the file with column named "User Name". The biggest problem for me to solve is that data in this column consists of last name and first name of person in totally mixed format. For example:
"User Name"
John Smith
Carter Mike
Garfield, Tom
And so on...
I've got the second file which contains data in the proper format, I've got there 3 columns: "Last Name", "First Name" and "Id". What I need to do is to copy the Id that match the person from the second file to the first file.
My idea was to loop through "User Name" column and compare it using InStr function with at first "Last Name" column and if it matches to compare with "First Name" column. Then if there is a match I would copy Id to the column "B" in the first file. But it turned out that I'm too weak in VBA.
Here is what I've written. It doesn't work at all, but maybe will help you to understand what my problem is:
Option Explicit
Sub FindID()
Dim rLastCell, rFirstCell, rUserCell As Range
Dim LastCell, FirstCell, UserCell As Range
Dim file As Workbook
Dim i As Long
'open file to compare
Set file = Workbooks.Open(Filename:=ThisWorkbook.Path & "\gooddata.xls")
'set last used cell
Set rLastCell = file.Worksheets("Sheet1").Range("A65536").End(xlUp)
Set rFirstCell = file.Worksheets("Sheet1").Range("B65536").End(xlUp)
Set rUserCell = ThisWorkbook.Worksheets("Sheet1").Range("C65536").End(xlUp)
With ThisWorkbook.Sheets("Sheet1")
For Each UserCell In .Range("C2:C" & rUserCell.Row)
For Each LastCell In file.Sheets("Sheet1").Range("A2:A" & rLastCell.Row)
If InStr(0, UserCell.Value, LastCell.Value, vbTextCompare) <> 0 Then
For Each FirstCell In file.Sheets("Sheet1").Range("B2:B" & rFirstCell.Row)
If InStr(0, UserCell.Value, FirstCell.Value, vbTextCompare) <> 0 Then
'copy id from gooddata.xls to baddata.xls
End If
Next FirstCell
End If
Next LastCell
Next UserCell
End With
file.Close savechanges:=True
Set file = Nothing
End Sub
Thanks for any advice.
Upvotes: 2
Views: 4076
Reputation: 5370
Given that:
My advice is to use excel itself more than VBA. Specifically the VLOOKUP() function. If you do there are 2 ways to go with this
The first:
The second is to do it the other way around:
If you make sure to create proper formula's you could simply paste in new 'bad data' in the username column for subsequent datasets
Upvotes: 3