Excel VBA函数无法设置范围

SPl*_*ten 2 excel vba range

我编写了一个带有两个参数的 VBA 函数,第一个是字符串,第二个是范围,在工作表中指定为:

=strPack(B1,G3)
Run Code Online (Sandbox Code Playgroud)

在代码中,该例程声明为:

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
Run Code Online (Sandbox Code Playgroud)

我尝试过 .Value、.Value2 和 .Text,都导致错误:

Application-defined or object-defined error
Run Code Online (Sandbox Code Playgroud)

当我查看调试器时,strHex 和 rngCnt 都是有效且正确的。为什么我无法分配范围以及如何修复它?

错误处理程序不是问题所在,请尝试一下,它工作得非常好,并且是在发生错误时拾取错误并中止函数的标准方法。

[编辑]我刚刚尝试了以下操作:

Public Sub updateCount()
    Worksheets("Sheet1").Range("G3").Value = CStr(intProcessed)
End Sub
Run Code Online (Sandbox Code Playgroud)

intProcessed 对于模块来说是全局的,并且是一个整数,结果是相同的,完全相同的错误。

[Edit2] 我想删除这篇文章,因为我现在更改了方法来调用另一个子例程,该子例程返回一个放入单元格的值。我无法删除它!感谢大家的帮助。

cyb*_*shu 5

看代码注释:

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
Run Code Online (Sandbox Code Playgroud)

  • 冷静下来。阅读此https://support.microsoft.com/en-nz/help/170787/description-of-limitations-of-custom-functions-in-excel (3认同)