在Excel中编写VBA公共用户定义函数

4

I have created the function below:

Option Explicit
Public Function fyi(x As Double, f As String) As String

Application.Volatile
Dim data As Double
Dim post(5)
    post(1) = "Ribu "
    post(2) = "Juta "
    post(3) = "Milyar "
    post(4) = "Trilyun "
    post(5) = "Ribu Trilyun "
Dim part As String
Dim text As String
Dim cond As Boolean
Dim i As Integer

If (x < 0) Then
fyi = " "
Exit Function
End If

    If (x = 0) Then
    fyi = "Nol"
    Exit Function
    End If

        If (x < 2000) Then
        cond = True
        End If
        text = " "

            If (x >= 1E+15) Then
            fyi = "Nilai Terlalu Besar"
            Exit Function
            End If

For i = 4 To 1 Step -1
data = Int(x / (10 ^ (3 * i)))
    If (data > 0) Then
    part = fyis(data, cond)
    text = text & part & post(i)
    End If
x = x - data * (10 ^ (3 * i))
Next
    text = text & fyis(x, False)
    fyi = text & f
End Function
Function fyis(ByVal y As Double, ByVal conds As Boolean) As String

Dim datas As Double
Dim posts(2)
    posts(1) = "Puluh"
    posts(2) = "Ratus"
Dim parts As String
Dim texts As String
'Dim conds As Boolean
Dim j As Integer
Dim value(9)
    value(1) = "Se"
    value(2) = "Dua "
    value(3) = "Tiga "
    value(4) = "Empat "
    value(5) = "Lima "
    value(6) = "Enam "
    value(7) = "Tujuh "
    value(8) = "Delapan "
    value(9) = "Sembilan "

texts = " "
For j = 2 To 1 Step -1
datas = Int(y / 10 ^ j)
    If (datas > 0) Then
    parts = value(datas)
        If (j = 1 And datas = 1) Then
        y = y - datas * 10 ^ j
            If (y >= 1) Then
            posts(j) = "belas"
            Else
            value(y) = "Se"
            End If
        texts = texts & value(y) & posts(j)
        fyis = texts
        Exit Function
        Else
        texts = texts & parts & posts(j)
        End If
    End If
y = y - datas * 10 ^ j
Next
    If (conds = False) Then
    value(1) = "Satu "
    End If
texts = texts & value(y)
fyis = texts
End Function

当我回到Excel并在单元格中键入=fyi(500,"USD")时,它会返回#name
请告知我如何解决。
5个回答

11

把这样的功能放在Addin里是最合适的地方...

要创建一个Addin:

新建一个工作簿

按alt+F11

创建一个模块,命名为MyFunctions或其他有意义的名称

把你的函数放进去

完成以上步骤后,将工作簿另存为ExcelAddin (.xlam)并关闭它。 转到Excel选项(或工具/addins),选择你的addin(或转到addins选项卡,点击Go然后在Excel 07中查找它)

现在你的函数将始终可用于每个工作簿,无需添加前缀。


你如何给一个模块命名?当我创建它时,它只被命名为“Module”,而当我<右键单击>它时,上下文菜单没有提供“重命名”选项。 - Alexis
1
@Alexis,当您选择模块名称时,窗口下方将有一个部分,允许您编辑模块属性,包括名称。单击并编辑名称,然后按回车键即可重命名。 - Starfish

7
如果你的UDF在另一个工作簿中,而不是你所调用的工作簿中,则需要在UDF前面添加工作簿名称。例如:
=PERSONAL.XLS!fyi(500,"USD")

1
不确定我会使用这种方法...但是对于深奥的UDF知识,Dick加一分! - Mark Nold

6

3

确保你的函数在模块中,而不是工作表中。


-2

检查一下错别字:函数应该是fyi而不是fyis

看一下最后一行的fyis = texts,应该改为fyi = texts


“fyis”也是问题代码中的一个函数。 - Artjom B.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接