Excel - 为什么我的用户定义函数不起作用?

时间:2016-08-15 07:10:45

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

我正在尝试创建一个UDF来获取单元格的.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])格式调用它。

2 个答案:

答案 0 :(得分:0)

读取.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
'''

答案 1 :(得分:0)

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

提要:不要在Microsoft Excel对象中创建函数;创建一个单独的模块并将其放在此处。