Home » excel » excel – VBA lookup refer to first sheet in workbook not "Sheet1"

excel – VBA lookup refer to first sheet in workbook not "Sheet1"

Posted by: admin May 14, 2020 Leave a comment

Questions:

How would I change the below lookup to refer to the first sheet in the workbook and not ‘Sheet 1’?

.Range("I15:I" & lastRow).FormulaR1C1 = _
                       "=IF(VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "]Sheet1!C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "]Sheet1!C1:C2,2,TRUE),NA())"

Thanks

How to&Answers:

You are concatenating already the workbook name into the formula. The same way you could concatenating the name of the first worksheet too. The first worksheet is the first sheet in workbook’s Worksheets collection.

So combinedWorkbook.Worksheets(1).Name would be the name of the first worksheet in workbook combinedWorkbook.

But names could containing spaces like “My Worksheet Name”. Then the reference itself must be within single quotes like 'My Worksheet Name'!A1.

So all together:

.Range("I15:I" & lastRow).FormulaR1C1 = _
                       "=IF(VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]" & combinedWorkbook.Worksheets(1).Name & "'!C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]" & combinedWorkbook.Worksheets(1).Name & "'!C1:C2,2,TRUE),NA())"

Answer:

if you are going to re-use it then I would declare:

Dim first_sheet As String
first_sheet = combinedWorkbook.Sheets(1).Name

And then use it in your code like this:

.Range("I15:I" & lastRow).FormulaR1C1 = _
                       "=IF(VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "] & first_sheet & !C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "] & first_sheet  & !C1:C2,2,TRUE),NA())"

Answer:

This is really a small example how to refer to the first worksheet.

  1. Take the name of the first worksheet and save it as a variable, using the .Name property.

  2. Concatenate the variable in the formula:


Public Sub TestMe()

    Dim wks1 As String
    wks1 = Worksheets(1).Name
    'worksheets should not contains spaces! :) left and right
    Worksheets(1).Name = Trim(wks1)
    Range("I15:I20").FormulaR1C1 = "=" & wks1 & "!R1C1"

End Sub