VBA – 呼叫子function(模块)
我在VBA
有以下function:
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
现在我需要的是从一个macros或者更好的macros开始调用这个函数,所以我可以把它和excel
工具栏上的自定义button关联起来。 任何人都可以指导我?
实际上,如果你在模块内部有这个函数,你可以直接在工作表单元格中引用它,就像你使用Excel的公式一样。
=lorh(A1)
为了使您的代码从macrosbutton运行,它需要是一个Sub而不是一个Function
我认为下面的代码会按照你想要的方式工作,我删除了多余的部分以及Barranka。
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
这个macros将使用活动单元格的值,就像你在函数中使用custo参数一样。
如果你需要在你的excel表单中使用你的函数,你只需要在任何单元格中写入,就像andrux所说的那样。
如果你需要从一个子文件中调用它,你只需要编写它:
public sub aSubprocedure() ' Any variables and other instructions go here var = lorh(input) ' Your code goes on end sub
然后你可以将你的子程序分配给你的button。
针对您的代码的一些build议:
我build议下面的“清理”你的function:
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
。
希望这可以帮助你