VBA - 在子(模块)内调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12963271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA - Call function inside a sub (module)
提问by Welisson Goldmann
I have the following function in VBA
:
我有以下功能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
Now what I need is to call this function starting from a sub or better from a macro, so I can associate it to a custom button on the excel
toolbar . Can anyone guide me?
现在我需要的是从 sub 或更好的宏开始调用此函数,以便我可以将它关联到excel
工具栏上的自定义按钮。任何人都可以指导我吗?
回答by andrux
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.
实际上,如果您在模块中拥有该函数,则可以在工作表单元格中直接引用它,就像使用 Excel 的公式一样。
=lorh(A1)
In order for your code to run from a macro button, it needs to be a Subinstead of a Function
为了让您的代码从宏按钮运行,它需要是一个Sub而不是一个函数
I think the code below would work the way you want it, I removed redundant pieces as well as Barranka did.
我认为下面的代码会按照你想要的方式工作,我和 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
This macro would use the active cell value the same way you were using the custoparameter in your function.
此宏将使用活动单元格值的方式与您在函数中使用custo参数的方式相同。
回答by Barranka
If you need to use your function in your excel sheet, you only need to write it at any cell, just as andrux said.
如果你需要在你的excel表格中使用你的函数,你只需要在任何一个单元格写上它,就像andrux所说的。
If you need to call it from a sub, again, you only need to write it:
如果您需要从子中调用它,再次,您只需要编写它:
public sub aSubprocedure()
' Any variables and other instructions go here
var = lorh(input)
' Your code goes on
end sub
Then you can assign your subprocedure to your button.
然后您可以将您的子过程分配给您的按钮。
A few suggestions for your code:
对您的代码的一些建议:
I suggest the following 'clean up' for your 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
Notice that if custo <= 0 or custo < 0
is redundant... you only need custo<=0
.
请注意,这if custo <= 0 or custo < 0
是多余的……您只需要custo<=0
.
Hope this helps you
希望这对你有帮助