I am trying to open a workbook so I can read data from it and populate fields in another worksheet. When I run the code, it isn't detecting the workbook or opening it. The workbook is on a shared drive and must be opened read only.
When I tried to set "wb", a workbook variable, set wb = Workbooks("filepath")
, when debugging it is showing wb = Empty.
I changed the code slightly to use a With statement instead, but still have the same problem. The code jumps from the With Workbooks.Open
to the line below, then back and forth between the two forever, not allowing me to close the workbook.
I eventually have to force close and reopen the file. I can break the code, but it immediately starts the function again without giving me a chance to save or close the workbook. Code below, please help me understand what is happening.
[EDIT]: When I first manually open the parts book, then replace the Workbooks.Open
line with this code: Set wb = Workbooks("New Parts Book - Official.xlsx")
and type the function into a cell, I have no issues and it works just fine (also requires declaration Dim wb as Workbook
). The cell formula looks like this: =Lookup_By_PN([@[Part Number]],"name")
where the part number argument is coming from a named table column on the same row as the function cell.
Function Lookup_By_PN(ByVal PN As String, Optional ByVal returnField As String = "Price") As Variant
Dim vCell As Variant, result As Variant
result = ""
With Workbooks.Open(Filename:="Z:\Shared\Materials\Parts Book\New Parts Book - Official.xlsx", UpdateLinks:=0, ReadOnly:=1)
For Each vCell In .Sheets("PARTS BOOK").Range("$F$260:$F$3872")
With vCell
If InStr(1, .Value2, PN, vbTextCompare) > 0 Then
Select Case True
Case InStr(1, returnField, "Price", vbTextCompare) > 0
If IsNumeric(.Offset(, 3).Value2) Then
result = .Offset(, 3).Value2
Else
result = .Offset(, 2).Value2
End If
Case InStr(1, returnField, "Name", vbTextCompare) > 0
result = .Value2
Case InStr(1, returnField, "Size", vbTextCompare) > 0
Dim quotePosR As Integer, spacePosL As Integer
quotePosR = InStr(1, .Value2, """", vbTextCompare)
spacePosL = InStrRev(.Value2, " ", quotePosR, vbBinaryCompare)
result = Evaluate(Replace(Mid(.Value2, spacePosL + 1, quotePosR - spacePosL - 1), "-", "+", compare:=vbTextCompare))
Case InStr(1, returnField, "Type", vbTextCompare) > 0
result = .Offset(, -2).Value2
Case Else
result = "Not Found"
End Select
End If
End With
Next vCell
End With
Lookup_By_PN = result
End Function