我创建了一个使用源 excel 文件的 UDF,将数据作为 UDF 结果。
但是,即使我使用 .close 方法输入下面的"with"代码,源文件也不会关闭。
使用后关闭源文件的任何帮助将不胜感激,非常感谢!
sfilename = "R:values only.xlsb"
Application.DisplayAlerts = False
With GetObject(sfilename)
range1 = .Sheets("RawData").Range("A:B")
If IsError(Application.VLookup(lookupval, range1, 2, False)) Then
If IsError(Application.VLookup(lookupval2, range1, 2, False)) Then
MsgBox "Pair or date does not exist!"
Else
getex = 1 / Application.VLookup(lookupval2, range1, 2, False)
End If
Else
getex = Application.VLookup(lookupval, range1, 2, False)
End If
.Close
End With
Application.DisplayAlerts = True
如上面的评论所述,您可以在另一个实例中打开文件(在同一实例中,您的 UDF 公式调用将不起作用(
Set objExcel = CreateObject("Excel.Application")
With objExcel
.Visible = False
.DisplayAlerts = False
With .Workbooks.Open(sfilename)
range1 = .Sheets(2).Range("A:B")
If IsError(Application.VLookup(lookupval, range1, 2, False)) Then
If IsError(Application.VLookup(lookupval2, range1, 2, False)) Then
MsgBox "Pair or date does not exist!" 'do not use msgbox but give getex a string => getex = "error"
Else
getex = 1 / Application.VLookup(lookupval2, range1, 2, False)
End If
Else
getex = Application.VLookup(lookupval, range1, 2, False)
End If
.Close
End With
.Quit
End With
另一种可能性是通过 Sub 将 UDF 的结果放在工作表中(我会这样做(