I am matching two columns in a new workbook with two columns in Workbook 2, and then retrieving column B from Workbook2 and copying it to column B in the new workbook. Some cells will be empty.
VBA Code:
Sub InsertDeviceName_NewBook()
Dim w1 As Worksheet, w2 As Worksheet, wsnew As Worksheet
Dim wbnew As Workbook
Dim c As Range, FR As Variant
Dim d As Range
Dim e As Range 'rng1 As Range, rng2 As Range
Dim lr1 As Long, lr2 As Long
Dim x As Long, i As Long, lr As Long
Dim rng1 As Variant, rng2 As Variant
Dim vals()
Application.ScreenUpdating = False
Set w2 = Workbooks("Book2.xlsx").ActiveSheet
Set w1 = Workbooks("Book1.xlsx").ActiveSheet
w1.Range("B:D").Copy
Set wbnew = Workbooks.Add
Columns("A:A").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Name = w1.Name
Set wsnew = wbnew.ActiveSheet
lr1 = wsnew.Cells(Rows.count, 1).End(xlUp).Row
lr2 = w2.Cells(Rows.count, 1).End(xlUp).Row
wsnew.Sort.SortFields.Add2 Key:=Range("B1"), _
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With wsnew.Sort
.SetRange Range("A1:C" & lr1)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("B:B").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").Select
ActiveCell.FormulaR1C1 = "Device Name"
rng1 = wsnew.Range("C2", wsnew.Range("D" & wsnew.Cells(Rows.count, 1).End(xlUp).Row)).Value
rng2 = w2.Range("C2", w2.Range("D" & w2.Cells(Rows.count, 1).End(xlUp).Row)).Value
ReDim vals(1 To UBound(rng1, 1), 1)
For x = 1 To UBound(rng1, 1)
For i = 1 To UBound(rng2)
If rng1(x, 2) = rng2(i, 2) Then
If rng1(x, 3) = rng2(i, 3) Then 'causes error
vals(x, 0) = rng2(i, 2)
GoTo Nextone
End If
End If
Next i
Nextone:
Next x
ws1.Range("B2").Resize(UBound(vals, 1), 1).Value = vals
Application.ScreenUpdating = True
End Sub