Reference variable worksheet in VLOOKUP vba

▼魔方 西西 提交于 2019-12-22 12:03:19

问题


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!


回答1:


Try this (UNTESTED - Just typed it here)

Range("O2").FormulaR1C1 = "=VLOOKUP(RC[-1]," & ws.name & "!C[-14],1,FALSE)"


来源:https://stackoverflow.com/questions/10142726/reference-variable-worksheet-in-vlookup-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!