[英]#Value error while accessing user defined function in VBA
Code works fine when I access function from VBA however when I call the same function in excel cell ( postalcode("23.0776120,72.6538530")
, I get #Value error. My code is: 当我从VBA访问函数时,代码工作正常,但是当我在excel单元格中调用相同的函数( postalcode("23.0776120,72.6538530")
,出现postalcode("23.0776120,72.6538530")
错误。我的代码是:
Function PostalCode(latlng As String) As String
Dim xmlDoc As MSXML2.DOMDocument60
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xParent As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim Col, Row As Integer
Set xmlDoc = New MSXML2.DOMDocument60
xmlDoc.async = False
xmlDoc.validateOnParse = False
' use XML string to create a DOM, on error show error message
If Not xmlDoc.Load("https://maps.googleapis.com/maps/api/geocode/xml?latlng=" & latlng) Then
Err.Raise xmlDoc.parseError.ErrorCode, , xmlDoc.parseError.reason
End If
Set xEmpDetails = xmlDoc.DocumentElement
Set xParent = xEmpDetails.FirstChild
Row = 1
Col = 1
Dim xmlNodeList As IXMLDOMNodeList
Set xmlNodeList = xmlDoc.SelectNodes("//formatted_address")
Worksheets("Sheet1").Cells(1, 6).Value = xmlNodeList.Item(0).Text
Dim xyz As String
PostalCode = xmlNodeList.Item(0).Text
' PostalCode = "Not Found (try again, you may have done too many too fast)"
MsgBox PostalCode
End Function
It's a documented limitation of User-Defined Functions that you cannot generally operate on or manipulate range/worksheet objects within a UDF called from the worksheet. 这是用户定义函数的有据可查的限制 ,您通常不能在从工作表调用的UDF中操作或操作范围/工作表对象。 While you can do most value/property queries, you can't change the environment: 虽然您可以进行大多数价值/资产查询,但不能更改环境:
A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. 在工作表单元格中由公式调用的用户定义函数不能更改Microsoft Excel的环境。 This means that such a function cannot do any of the following: 这意味着该功能不能执行以下任何操作:
- Insert, delete, or format cells on the spreadsheet. 在电子表格上插入,删除或格式化单元格。
- Change another cell's value. 更改另一个单元格的值。
- Move, rename, delete, or add sheets to a workbook. 移动,重命名,删除工作表或将其添加到工作簿。
- Change any of the environment options, such as calculation mode or screen views. 更改任何环境选项,例如计算模式或屏幕视图。
- Add names to a workbook. 将名称添加到工作簿。 Set properties or execute most methods. 设置属性或执行大多数方法。
I suspect that stepping through this code using F8 key in the VBE will identify the error, probably Worksheets("Sheet1").Cells(1,6).Value
. 我怀疑在VBE中使用F8键单步执行此代码将识别错误,可能是Worksheets("Sheet1").Cells(1,6).Value
。
The basic rationale behind this limitation is to prevent infinite loops/circular references. 此限制的基本原理是防止无限循环/循环引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.