Excel VBA - 将字符串作为代码执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13072918/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:14:28  来源:igfitidea点击:

Excel VBA - Execute string as code

excelvba

提问by Sparked

I am trying to execute the following string as code using Evaluate but get Error 2029. Anyone know why?

我正在尝试使用 Evaluate 将以下字符串作为代码执行但得到错误 2029。有人知道为什么吗?

Help much appreciated.

非常感谢帮助。

Calculation = "Format(""21/08/2012"", ""MMM"")"
Value = Evaluate(Calculation)

回答by nutsch

Try instead

试试吧

Calculation = "TEXT(""21/08/2012"", ""MMM"")"

EVALUATE converts formulas to results, and FORMAT is a VBA function. The formula equivalent is TEXT.

EVALUATE 将公式转换为结果,FORMAT 是一个 VBA 函数。等价的公式是 TEXT。

You can also skip the evaluate and use the FORMAT function on the date directly.

您也可以跳过评估并直接在日期上使用 FORMAT 函数。

回答by Stepan1010

You can use most worksheet functions in VBA directly with Application.WorksheetFunction.- for example - try this out:

您可以直接在 VBA 中使用大多数工作表函数Application.WorksheetFunction.- 例如 - 试试这个:

Sub DateExample()

Dim StringTest As String
StringTest = Application.WorksheetFunction.Text("12/08/2012", "MMM")

Cells(1, 1).Value = StringTest

End Sub

Good Luck

祝你好运