简体   繁体   English

如何在 VBA 中使用 Excel 公式?

[英]How to use Excel Formulas in VBA?

I want to put this formula into VBA.我想把这个公式放到 VBA 中。

=IFERROR(AP24728<0,(NETWORKDAYS(B24728,AQ24728,'N:#Abe\\Report PU\\Desember[Report PU 05 Des 2016.xlsx]Holidays'!$A$2:$A$69))-1) =IFERROR(AP24728<0,(NETWORKDAYS(B24728,AQ24728,'N:#Abe\\Report PU\\Desember[Report PU 05 Des 2016.xlsx]Holidays'!$A$2:$A$69))-1)

Based on your answer to "What are you trying to do?"基于你对“你想做什么?”的回答。 of "I want to put this formula into VBA", some sample code might be: “我想将此公式放入 VBA”中,一些示例代码可能是:

Dim result As Variant
result = Evaluate("IFERROR(AP24728<0,(NETWORKDAYS(B24728,AQ24728,'N:#Abe\Report PU\Desember[Report PU 05 Des 2016.xlsx]Holidays'!$A$2:$A$69))-1)")

If you provide additional details in your question, I can expand on this answer, or someone else may come up with a much better way.如果您在问题中提供更多详细信息,我可以扩展此答案,或者其他人可能会想出更好的方法。

To use Excel formula in VBA you have two choices: you can either Evaluate the function string as in @YowE3K's example given here, or alternatively you can use the WorksheetFunction method to perform most Excel functions.要在 VBA 中使用 Excel 公式,您有两种选择:您可以像此处给出的@YowE3K 示例中那样Evaluate函数字符串,或者您可以使用WorksheetFunction方法来执行大多数 Excel 函数。 The Evaluate method is best if you want to do a fixed formula like your example suggests and return the result in VBA, the WorksheetFunction method allows you to specify the arguments in VB language, which (in my opinion) is better for a dynamic function (there is however a trade-off in terms of speed if you're trying to do this multiple times, such as iterating over a range of cells etc.) However, since you have another function embedded in the IfError , you'd need to nest another WorksheetFunction within the IfError one, like below:如果您想像示例中建议的那样执行固定公式并在 VBA 中返回结果,则Evaluate方法是最好的, WorksheetFunction方法允许您以 VB 语言指定参数,这(在我看来)更适合动态函数(但是,如果您尝试多次执行此操作(例如迭代一系列单元格等),则会在速度方面进行IfError 。)但是,由于您在IfError嵌入了另一个函数,因此您需要在IfError嵌套另一个WorksheetFunction ,如下所示:

WorksheetFunction.IfError([expression], WorksheetFunction.NetworkDays([date from], [date to], [holidays]))

However, it is not clear from your post what you want to do.但是,从您的帖子中不清楚您想做什么。 The key thing here would be to provide some further information about what you are trying to do overall - ie what is the 'big picture' that you're trying to achieve?这里的关键是提供一些关于您总体上尝试做的事情的进一步信息 - 即您想要实现的“大局”是什么? Do you just want to test the value in one cell?您只想测试一个单元格中的值吗? Will this be something that you need to repeat for multiple cells?这是您需要为多个单元格重复的操作吗? Why do you need to do this in VBA, when you could much more easily use the formula in a worksheet?当您可以更轻松地在工作表中使用公式时,为什么需要在 VBA 中执行此操作?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM