【问题标题】:How to call user-defined function in Personal.xlsb?如何在 Personal.xlsb 中调用用户自定义函数?
【发布时间】:2016-12-21 09:36:54
【问题描述】:

我正在尝试获取单元格的.NumberFormat

我尝试将 UDF 放入我正在使用它的项目和我的 PERSONAL.XLSB
我尝试将它们声明为FunctionPublic Function,但都没有被识别。我得到一个#NAME?错误。

函数,在 PERSONAL.XLSB 中。

Public Function GetFormat(r As Range) As String
    GetFormat = r.NumberFormat
End Function

我已经通过this page。我无法弄清楚缺少什么。

编辑:如果我指定 PERSONAL.XLSB!GetFormat,它就可以工作,但我希望能够仅使用 =GetFormat([CELL]) 格式调用它。

【问题讨论】:

  • 尝试在调用函数前加上 Personal.xlsb!
  • 这行得通,是的 - 但有什么方法可以设置它,以便我可以像使用任何普通 Excel 函数一样使用它?
  • 它在Module 中吗?
  • 目前,是的 - 在我的 PERSONAL.XLSB 的一个模块中。我也试过把它放在工作簿本身和工作表自己的代码中。
  • 为避免使用工作簿名称作为前缀,它必须位于您在单元格中使用它的同一工作簿中,或者位于加载项中。它还必须在普通模块中,并且该模块不应与函数同名。

标签: excel excel-formula user-defined-functions vba


【解决方案1】:

读取 .NumberFormat 属性返回非字符串和非信息性 Null 以进行多种格式的多项选择。请看:

'''''''
Public Function GetFormat(r As Range) As String
Dim rTmp As Range
    Select Case (Selection.Address = r.Address)
        Case True
            Set rTmp = ActiveCell ' #1 - for selection
        Case False
            Set rTmp = r(1)       ' #2 - for referenced range, having no active cell
    End Select
    GetFormat = rTmp.NumberFormat
    Stop
End Function

Private Sub sb_Test_GetFormat() ' for test purposes
Dim rTmp As Range, rSel As Range
    Set rSel = Selection ' save current Selection

    ' assign reference to any temporary Range with multiple formats
    Set rTmp = Range("$C$17:$C$27")

    rTmp.Select ' Select our tmp Range
    Debug.Print GetFormat(Selection)         ' #1 - work with Range as Selection
    rSel.Select ' restore Selection

    Cells(1).Select ' Move selection to rTmp independent area
    Debug.Print GetFormat(rTmp)              ' #2 - work with not selected Range
    rSel.Select ' restore Selection

    Debug.Print GetFormat(rTmp.Offset(1, 1)) ' #2 -work with other not selected Range

    Stop
End Sub
'''

【讨论】:

  • 谢谢,但我的功能工作正常 - 问题只是让它工作而不需要工作簿参考。最后,我暂时只使用了工作簿参考。
【解决方案2】:

答案可能在这里:https://stackoverflow.com/a/16296990/3285233

概要:不要在 Microsoft Excel 对象中创建函数;创建一个单独的模块并将它们放在那里。

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多