Reputation: 171
I am writing a macro that creates variable worksheets based on a value on an existing worksheet. I managed that part fine, but now I need to add a VLOOKUP formula on another sheet that references the newly created sheets. There is no set pattern to the name of the new worksheets, so I having trouble referencing them. Here is the code I used to create the new worksheets:
Dim ws As Worksheet
Dim rngCriteria As Range
Dim sName As String
Dim I As Long
Dim LastRow As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
With Sheets("Part Type REC")
If .AutoFilterMode = True Then .AutoFilterMode = False
.Range("D1:D" & LastRow).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=.Range("J1"), Unique:=True
Set rngCriteria = .Range("J1").CurrentRegion
For I = 2 To .Cells(Rows.Count, "J").End(xlUp).Row
sName = .Cells(I, "J")
Set ws = ThisWorkbook.Worksheets.Add
ws.Name = sName
.Range("D1:D" & LastRow).AutoFilter Field:=1, Criteria1:="=" & .Cells(I, "J").Value
.Range("A1:H" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("A1")
Next I
.AutoFilterMode = False
End With
Sheets("Part Type REC").Select
Columns("J:J").Select
Selection.ClearContents
Range("A1").Select
And here is the VLOOKUP that I need to reference the new worksheets:
Sheets("TP Parts").Select
Range("O2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],'ws.name'!C[-14],1,FALSE)"
Range("O2").Select
Where am I going wrong with this?
Thanks in advance!
Upvotes: 2
Views: 8363
Reputation: 149277
Try this (UNTESTED - Just typed it here)
Range("O2").FormulaR1C1 = "=VLOOKUP(RC[-1]," & ws.name & "!C[-14],1,FALSE)"
Upvotes: 4