Wookbooks.open方法在编辑器中工作,但不能从Excel中工作

我想在VBA中开发一个返回结果到当前工作表的函数。 它的目的是打开另一个电子表格,提取一些数据,做一些处理,并返回一个值,调用该函数的工作表。

当我从VBA编辑器的“立即”窗口调用函数时,一切正常。 但是,当我将调用转移到工作表时,当尝试打开其他工作簿(AreaBook)时,函数行为偏离预期。 对象AreaBook仍然是一个没有任何东西的指针。

我已经努力编码的文件名; 再次调用函数从立即窗口工作,但不是从工作簿调用时。

有任何想法吗?

Public Function pointInWhichArea(FileName As String, SheetName As String, areaID As String, ByVal pointLong As Single, ByVal pointLat As Single) As Variant ', testPointLon As Single, testPointLat As Single) As Variant Dim a, b, c As Integer Dim colAreaID, colLat, colLon As Integer Dim AreaBook As Workbook Dim AreaSheet As Worksheet Dim polygonPoints() As pointType Dim testPoint As pointType Dim found As Boolean ' extract the point details testPoint.x = pointLong testPoint.y = pointLat ' set the workbook and sheet objects FileName = filePath + FileName ' open the Area definition file Set AreaBook = Workbooks.Open(FileName) ' <<<< PROBLEM HERE Set AreaSheet = AreaBook.Sheets(SheetName) a = 1 ' identify the Polygon ID, latitude and longitude columns column While AreaSheet.Cells(1, a).Value <> "" Select Case Worksheets(SheetName).Cells(1, a).Value Case Is = areaID colAreaID = a Case Is = "Latitude" colLat = a Case Is = "Longitude" colLon = a End Select a = a + 1 Wend a = 2 ' loop through all points in the area list b = a ' remember the beginning of the polygon found = False While (AreaSheet.Cells(a, colAreaID).Value <> "" And found = False) If AreaSheet.Cells(a, colAreaID).Value <> AreaSheet.Cells(a + 1, colAreaID).Value Then ' test for the end of this polygon c = a ' remember the end of the polygon ReDim polygonPoints(b To c) As pointType ' array to capture the poylgon For a = b To c ' loop through each point polygonPoints(a).x = AreaSheet.Cells(a, colLon).Value ' extract the longitude of the point polygonPoints(a).y = AreaSheet.Cells(a, colLat).Value ' extract the latitude of the point Next a b = a ' remember the beginning of the next polygon If pointInArea(testPoint, polygonPoints) = True Then ' test if the point is in the current polygon pointInWhichArea = AreaSheet.Cells(a - 1, colAreaID).Value ' return the area label found = True End If Else a = a + 1 End If Wend AreaBook.Close End Function 

恐怕工作表函数不能用于影响其他单元格或工作簿 – 您不能将函数添加到单元格A1,并期望结果出现在单元格B2中。 以同样的方式,您不能在单元格A1中添加一个函数,并期望它打开另一个工作簿来获得答案。

这就是为什么它在即时窗口而不是Excel函数。 您可能能够定义到另一个工作簿的链接,然后引用该链接,但是您不能获取该function来物理打开其他工作簿。

工作表函数(以及这些函数的用户定义的变体)在它们可以做什么以及不可以做什么方面都是有限的,下面是关于这个问题的一个微软文章的小节选:

https://support.microsoft.com/en-us/kb/170787

由工作表单元格中的公式调用的用户定义的函数不能更改Microsoft Excel的环境。 这意味着这样的function不能做到以下任何一项:

  • 在电子表格中插入,删除或格式化单元格。
  • 更改另一个单元格的值。
  • 移动,重命名,删除或将工作表添加到工作簿。
  • 更改任何环境选项,例如计算模式或屏幕视图。
  • 将名称添加到工作簿。
  • 设置属性或执行大多数方法。

该网页继续指出:

任何环境变化都应该通过使用Visual Basic子程序来完成。


所以简而言之,你不能做你正在试图做的工作表UDF (用户定义函数) ,并需要将其更改为子例程。