1

我有以下功能VBA

Public Function lorh(custo As Integer)
If custo > 10.99 And custo <> 0 Then
    lorh = "1.4"
Else
    If custo < 11 And custo <> 0 Then
        lorh = "1.35"
    Else
        If custo <= 0 Or custo < 0 Then
            lorh = "Valor Inválido"
        End If
    End If
End If
End Function

现在我需要的是从子开始调用这个函数,或者从宏开始调用这个函数,这样我就可以将它与excel工具栏上的自定义按钮相关联。谁能指导我?

4

2 回答 2

3

Actually, if you have that function inside of a module, you can directly reference it inside a worksheet cell, pretty much as you do with Excel's formulas.

=lorh(A1)

In order for your code to run from a macro button, it needs to be a Sub instead of a Function

I think the code below would work the way you want it, I removed redundant pieces as well as Barranka did.

Public Sub lorh()
    Dim lorh As String
    custo = ActiveCell.Value

    If custo > 10.99 Then
        lorh = "1.4"
    Else
        If custo > 0 Then
            lorh = "1.35"
        Else
            lorh = "Valor Inválido"
        End If
    End If

    ActiveCell.Value = lorh
End Sub

This macro would use the active cell value the same way you were using the custo parameter in your function.

于 2012-10-18T20:36:24.880 回答
1

如果你需要在你的excel表格中使用你的函数,你只需要写在任何一个单元格,就像andrux说的那样。

如果你需要从 sub 调用它,同样,你只需要编写它:

public sub aSubprocedure()
    ' Any variables and other instructions go here
    var = lorh(input)
    ' Your code goes on
end sub

然后您可以将您的子过程分配给您的按钮。


对您的代码的一些建议:

我建议为您的功能进行以下“清理”:

Public Function lorh(custo As Integer)
    If custo > 10.99 And custo <> 0 Then
        lorh = "1.4"
    Else If custo < 11 And custo <> 0 Then
        lorh = "1.35"
    Else If custo <= 0 Then
        lorh = "Valor Inválido"
    End If
End Function

请注意,这if custo <= 0 or custo < 0是多余的……您只需要custo<=0.

希望这可以帮助你

于 2012-10-18T20:53:14.410 回答