PDA

View Full Version : [SOLVED:] Problem with code



Zanaba1379
05-07-2015, 03:10 PM
Hey guys I received the below code off the internet and it works perfectly for what I need it to do and need some help trying to understand it more.



Sub replaceValue()Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet, lr As Long, c As Range, fn As Range
Set wb1 = Workbooks(1) 'Edit workbook name
Set wb2 = Workbooks(2) 'Edit workbook name
Set sh1 = wb1.Sheets(1) 'Edit sheet name
Set sh2 = wb2.Sheets(1) 'Edit sheet name
lr = sh1.Cells(Rows.Count, 2).End(xlUp).Row
For Each c In Range("B2:B" & lr)
Set fn = sh2.Range("B:B").Find(c.Value, , xlValues, xlWhole)
If Not fn Is Nothing Then
c = fn.Offset(0, 1).Value
End If
Next
Set fn = Nothing
End Sub


Where in the code does it tell excel where to look in WB2?

Example

Right now it is taking the value in WB1 column B2:B and searching WB2 column B:B to find a match, once it finds a match it then replaces the cell in column B on WB1 with whatever the value is in the cell on column C in WB2 next to the match.

Now i need to know how to change it so it will still search column B in WB2 but pull information from the cells in column A in WB2

I know the below part of the code tells it where to pull in WB1

lr = sh1.Cells(Rows.Count, 2).End(xlUp).Row
For Each c In Range("B2:B" & lr)

Thanks for any help you can offer!

mperrah
05-07-2015, 04:06 PM
Sub replaceValue()
Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet, lr As Long, c As Range, fn As Range
Set wb1 = Workbooks(1) 'Edit workbook name
Set wb2 = Workbooks(2) 'Edit workbook name
Set sh1 = wb1.Sheets(1) 'Edit sheet name
Set sh2 = wb2.Sheets(1) 'Edit sheet name
lr = sh1.Cells(Rows.Count, 2).End(xlUp).Row
For Each c In Range("B2:B" & lr)
Set fn = sh2.Range("B:B").Find(c.Value, , xlValues, xlWhole)
If Not fn Is Nothing Then
c = fn.Offset(0, 1).Value ' here is were it finds the match, you can say offset(0, -1) to use column A
End If
Next
Set fn = Nothing
End Sub

Zanaba1379
05-08-2015, 11:49 AM
Thank you mperrah. Worked perfectly once i knew what i was looking at.