在vba中将字符串计算为公式

时间:2017-10-03 14:11:37

标签: excel vba excel-vba

我正在尝试评估包含数据的excel单元格,

“AAA * 2”

然后在vba尝试使用

解决它们
class my_form extends moodleform {

    function definition() {
        $mform =& $this->_form;

        $mform->addElement('html', '<h2>' . get_string('header', 'local_data')  . '</h2>');

        global $USER;
        $userid = $USER->id;
        $myCourseIds = array();
        $selectArray = array();
        $myCourseIds = getMyCourses($userid);
      // push query results into selectArray as key, value
        foreach($myCourseIds as $myCourseId) {
            $key = $myCourseId->idnumber;
            $value = $myCourseId->shortname;
            $selectArray[$key] = $value;
        }

        $mform->addElement('select', 'courseid', get_string('courseid', 'local_data'), $selectArray);    

        $this->add_action_buttons(true, get_string('send', 'local_data'));
    }

}

我不知道这样的事情是否可能。如果这样会使我当前的项目更加简单。希望事先得到任何帮助。

2 个答案:

答案 0 :(得分:2)

你不能混合使用vba和字符串。

添加equation = replace(equation,"AAA", AAA)

dim AAA
dim equation
dim result
AAA=inputbox("?") 'some numeric value
equation=sheets("sheet1").range("A1").value 'contains "AAA*2"
equation = replace(equation,"AAA", AAA)
result=application.evaluate("=" & equation) 

答案 1 :(得分:2)

声明您的类型,并注意您对所涉及的值所做的隐含假设。

Dim userInput As Variant
userInput = InputBox("?") ' could be numeric, could be a null string pointer, could be anything.

If Not IsNumeric(userInput) Then Exit Sub

Dim AAA As Double
AAA = CDbl(userInput)

Dim source As Worksheet
Set source = ThisWorkbook.Worksheets("Sheet1")

Dim sourceEquation As Variant
sourceEquation = source.Range("A1").Value ' could be an error, an empty variant, a date, whatever

If IsError(sourceEquation) Then Exit Sub

Dim equation As String
'the "AAA" in the string is a string literal, doesn't refer to this local AAA variable.
equation = VBA.Strings.Replace(CStr(sourceEquation), "AAA", AAA)

Dim result As Double
result = Application.Evaluate("=" & equation)