VBA-Workbooks.Open卡在一个循环中,必须强制关闭

时间:2018-12-11 19:28:14

标签: excel vba

我正在尝试打开一个工作簿,以便可以从中读取数据并在另一个工作表中填充字段。当我运行代码时,它没有检测到工作簿或没有打开它。该工作簿位于共享驱动器上,并且必须以只读方式打开。

当我尝试设置“ wb”时,工作簿变量set wb = Workbooks("filepath")在调试时显示wb =空。

我稍稍更改了代码,改为使用With语句,但是仍然存在相同的问题。代码从With Workbooks.Open跳到下面的行,然后在两者之间永远来回移动,不允许我关闭工作簿。

我最终不得不强制关闭并重新打开文件。我可以破坏代码,但是它会立即再次启动该函数,而没有给我机会保存或关闭工作簿。下面的代码,请帮助我了解发生了什么。

[EDIT]:当我第一次手动打开零件手册,然后用以下代码替换Workbooks.Open行:Set wb = Workbooks("New Parts Book - Official.xlsx")并将函数键入单元格中时,我没有任何问题,它仅能正常工作很好(还需要声明Dim wb as Workbook)。单元格公式如下所示:=Lookup_By_PN([@[Part Number]],"name"),其中部件号参数来自与函数单元格在同一行的命名表列。

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

0 个答案:

没有答案