首页 > 解决方案 > 将 vba 函数的结果放在另一个 excel 单元格中

问题描述

我需要一个 VBA 函数,它将其结果之一存储在一个单元格中,而不是调用该函数的单元格中。我已成功将另一个单元格的地址传递给该函数。当从另一个 VBA 宏调用时,我的函数可以正常工作,但是当从 Excel 工作表中的单元格调用我的函数时,它会因 #VALUE 而崩溃!在调用单元格中,而不在目标单元格中​​放置任何内容。

当我单步执行我的函数时,我看到它正确地具有我想要放置值的单元格的地址。

Sub callMyFunc()     'when I call myFunc this way it works perfectly

    Dim theAddrRang As Range, resp%

    Set theAddrRang = Range("B17")

    resp = myFunc(theAddrRang)

    MsgBox "resp = " & resp

End Sub  



Function myFunc(addrR As Range) As Integer  
                        'If this function is called from worksheet it crashes
    Dim theAddr$, addrRstr$

    addrRstr = addrR.Address

    theAddr = "B14"

    MsgBox "Two address strings: " & addrRstr & "    " & theAddr

    Worksheets("Linda").Range(theAddr).Value = 44      'B14   crashes at this step

    Worksheets("Linda").Range(addrRstr).Value = 66     'B17

    myFunc = 88

End Function       

我希望函数 myFunc 将值 44 和 66 放入单元格 B14 和 B17 中。当我从另一个宏调用我的函数时,它工作得很好。当我在工作表上的单元格中输入以下内容时: =myFunc(B17) ,它会正确显示带有两个地址的消息框,然后在下一行代码中崩溃。(两个地址只是为了测试两者都有效;我真的只需要一个作为参数传递的地址。)

标签: excelvba

解决方案


...但这里有一个解决方法Evaluate

Function myFunc(addrR As Range) As Integer

    Dim wb, sht, addr

    'where is the target cell?
    addr = addrR.Address           'cell
    sht = addrR.Parent.Name        'sheet
    wb = addrR.Parent.Parent.Name  'workbook

    'pass the location of the cell to be updated and the value to be inserted
    Application.Evaluate "SetIt(""" & wb & """,""" & sht & """,""" & addr & """,99)"

    myFunc = 88 'return a value to the calling cell

End Function


'Calling this using evaluate seems to bypass the restrictions
'  Excel places on UDF's called from a worksheet
Function SetIt(wb As String, sht As String, addr As String, v)
    Workbooks(wb).Sheets(sht).Range(addr).Value = v
End Function

推荐阅读