我编写了一个带有两个参数的 VBA 函数,第一个是字符串,第二个是范围,在工作表中指定为:
=strPack(B1,G3)
在代码中,该例程声明为:
Public Function strPack(ByVal strHex As String, ByRef rngCnt As Range) As String
On Error Goto ErrHandler
If False Then
ErrHandler:
MsgBox Err.Description
Exit Function
End If
Dim intCnt As Integer
intCnt = 0
'...do something with strHex and increment intCnt whilst we go
rngCnt.Value = CStr(intCnt)
'strPack is populated by the body of the function
strPack = "Hello World"
End Function
我尝试过 .Value、.Value2 和 .Text,均导致错误:
Application-defined or object-defined error
当我查看调试器时,strHex 和 rngCnt 都是有效且正确的。为什么我无法分配范围以及如何修复它?
错误处理程序不是问题所在,请尝试一下,它工作得非常好,并且是在发生错误时发现错误并中止函数的标准方法。
[编辑]我刚刚尝试了以下操作:
Public Sub updateCount()
Worksheets("Sheet1").Range("G3").Value = CStr(intProcessed)
End Sub
intProcessed 对于模块来说是全局的,是一个整数,结果是相同的,错误完全相同。
[Edit2] 我想删除这篇文章,因为我现在更改了方法来调用另一个子例程,该子例程返回一个放入单元格的值。我无法删除它!感谢大家的帮助。
最佳答案
查看代码注释:
Public Function strPack(ByVal strHex As String, ByVal rngCnt As Range) As String
Dim lRes As Long
On Error GoTo errHandler
lRes = 1000 '==> Your business logic goes here
'/ This is the gymnastics you do to update range from an UDF
Application.Evaluate ("UpdateRange(" & rngCnt.Address & "," & lRes & ")")
strPack = "SUCCESSFULL"
errHandler:
If Err.Number <> 0 Then
strPack = "FAILED"
End If
End Function
'/ Helper to allow range update from UDF
Private Function UpdateRange(rngDest As Range, val As Variant)
rngDest.Value = val
End Function
关于Excel VBA函数无法设置范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53653359/