I have the below code, which I am having trouble with:
Sub getAccNos()
Dim oNameRange As Range
Dim oFindRng As Range
Dim sName As String
Dim sAccNo As String
Set oNameRange = Workbooks("New Name Work.xls").Worksheets("Manual").Range("B4")
Do While Not oNameRange.Text = ""
sName = Trim(oNameRange.Text)
Workbooks("New Name Work.xls").Worksheets("sheet1").Select
Set oFindRng = Cells.Find(What:=sName, After:=activecell)
Do While Not oFindRng Is Nothing
oNameRange.Offset(0, -1).Value = oFindRng.Offset(0, 1).Text
oFindRng.Offset(1, 0).Activate
Set oFindRng = Cells.Find(What:=sName, After:=activecell)
Loop
Set oNameRange = oNameRange.Offset(1, 0)
Loop
End Sub
Basically, on worksheet sheet1 I have a list of names with account number, and there can be several account numbers with the same name. On my target sheet, called Manual, I have the names .... but the account numbers are missing and I would like to get them.
I cannot use VLOOKUP because there are several names that are the same and I need to get a list of all the account numbers. How can I do this?
I tried to write the above code using FIND in VBA, unfortunately, I am missing something elementary as once in the inside Do Loop it just loops continuously when it should be stepping out (as for the first one there is only one occurrance)
thanks for showing me what I am doing wrong, or maybe a formula would be better?
Here is an example. What I would do is count how many occurrences, and then add another variable to increment for each occurrence, and
Loop While Not foundCount >= howManyInRange
Here is a simple code which doesn't loop through Sheet1 cells to find a match. It uses
.FIND
and.FINDNEXT
. More about it HERE.Place this code in a module and simply run it. This code is based on your sample file.
SCREENSHOT
Hope this is what you wanted?
I really really wanted to create something cool, sexy, snazzy, showy, elegant and clever using a Formula because I could, only it turned out that I couldn't, then it turned out I couldn't even get my Find logic to work, so I did it with a couple of nested loops then checked the results with formulas!