I am creating a VBA for the VLOOKUP function. I want to be able to capture a name and grade from Book 2 and have it display on Book1 based on the ID number, however, I keep getting error 91 even though I initialized the sht variable. Here is the code:
Sub vlookup1()
'Initializing workbook connection
Dim PathName As String
Dim FileName As String
Dim wkbk As Workbook
Dim sht As Worksheet
PathName = "K:\Kayla Data Auto-Population\VBA Experiment\"
FileName = "Book 2.xlsx"
Set wkbk = Workbooks.Open(PathName & FileName)
Set sht = wkbk.Worksheets("Sheet1") <- where error is occurring
'Initializing Variables
Set myrange = sht.Range("A:C")
Set ID = Range("A2")
Set Name = Range("B2")
Set Grade = Range("C2")
'Initializing VLOOKUP function
Name.Value = Application.WorksheetFunction.VLookup(ID, myrange, 2, False)
Grade.Value = Application.WorksheetFunction.VLookup(ID, myrange, 3, False)
End Sub
Sub vlookup1()
'Initializing workbook connection
Dim PathName As String
Dim FileName As String
Dim wkbk As Workbook
Dim sht As Worksheet
PathName = "K:\Kayla Data Auto-Population\VBA Experiment\"
FileName = "Book 2.xlsx"
Set wkbk = Workbooks.Open(PathName & FileName)
Set sht = wkbk.Worksheets("Sheet1") <- where error is occurring
'Initializing Variables
Set myrange = sht.Range("A:C")
Set ID = Range("A2")
Set Name = Range("B2")
Set Grade = Range("C2")
'Initializing VLOOKUP function
Name.Value = Application.WorksheetFunction.VLookup(ID, myrange, 2, False)
Grade.Value = Application.WorksheetFunction.VLookup(ID, myrange, 3, False)
End Sub