我正在使用在线教程教自己VBA。使用我到目前为止学到的东西,我制作了一个简单的BODMAS问题生成器。但是,我无法弄清楚如何计算生成的问题的答案。这就是我所做的:
Dim Indicator As String, Equation As String, IndicatorNum As Integer, RandNum As Integer, Answer As Integer
Type EqnStatements
Statement1 As Integer
Statement2 As Integer
Statement3 As Integer
End Type
Type Indicators
Indicator1 As String
Indicator2 As String
End Type
Private Sub IndicatorGenerator()
IndicatorNum = Int(Rnd * 4)
Select Case IndicatorNum
Case Is = 0
Indicator = "+"
Case Is = 1
Indicator = "-"
Case Is = 2
Indicator = "*"
Case Is = 3
Indicator = "/"
End Select
End Sub
Private Sub StatementGenerator()
RandNum = Int(Rnd * 10 + 1)
End Sub
Sub EquationGenerate()
Dim Eqn As EqnStatements, Ind As Indicators
StatementGenerator
Eqn.Statement1 = RandNum
StatementGenerator
Eqn.Statement2 = RandNum
StatementGenerator
Eqn.Statement3 = RandNum
IndicatorGenerator
Ind.Indicator1 = Indicator
IndicatorGenerator
Ind.Indicator2 = Indicator
Equation = Eqn.Statement1 & " " & Ind.Indicator1 & " " & Eqn.Statement2 & " " & Ind.Indicator2 & " " & Eqn.Statement3
Cells(2, 3) = Equation
End Sub
Sub AnswerShow()
Answer = Eqn.Statement1 & Ind.Indicator1 & Eqn.Statement2 & Ind.Indicator2 & Eqn.Statement3
Cells(3, 3) = Answer
End Sub
第一个主要Sub工作正常,并产生输出。当我运行第二个主子(AnswerShow)时,我收到一个错误:“需要对象”。我不知道如何使用存储在变量中的值来计算方程式。
答案 0 :(得分:0)
您需要面对'对象的原因'错误,是您尝试在Eqn
过程中使用变量AnswerShow
,但此变量不存在。
您在Eqn
过程中为对象变量EquationGenerate
的属性指定了值,但是在此过程完成运行后,此对象已从内存中丢失。
您必须将Eqn
对象变量传递到AnswerShow
过程才能访问属性。
我还建议使用函数生成数字,而不是使用公共变量的过程。见下面的代码。
Private Function Indicator() As String
Dim indicator_num As Integer
indicator_num = Int(Rnd * 4)
Select Case indicator_num
Case 0
Indicator = "+"
Case 1
Indicator = "-"
Case 2
Indicator = "*"
Case 3
Indicator = "/"
End Select
End Function
Private Function RandNum() As Integer
RandNum = Int(Rnd * 10 + 1)
End Function
Sub EquationGenerate()
Dim Eqn As EqnStatements, Ind As Indicators
Eqn.Statement1 = RandNum
Eqn.Statement2 = RandNum
Eqn.Statement3 = RandNum
Ind.Indicator1 = Indicator
Ind.Indicator2 = Indicator
Equation = Eqn.Statement1 & " " & Ind.Indicator1 & " " & Eqn.Statement2 & " " & Ind.Indicator2 & " " & Eqn.Statement3
Cells(2, 3) = Equation
AnswerShow Eqn, Ind
End Sub
Sub AnswerShow(ByRef Eqn As EqnStatements, ByRef Ind As Indicators)
Answer = Eqn.Statement1 & Ind.Indicator1 & Eqn.Statement2 & Ind.Indicator2 & Eqn.Statement3
Cells(3, 3) = Answer
End Sub
答案 1 :(得分:0)
您将字符'*','/','+'和' - '存储在名为“Indicator”的内存位置。然而,这并不能使它们成为指标的功能。
从理论上讲,您需要编写解释每个字符的代码,然后命令进行适当的计算:
`If Ind = "*" then Ans = x * y
在你的情况下,有一些额外的编码可以使序列正确。
VBA有一个评估函数(https://msdn.microsoft.com/en-us/library/office/ff193019.aspx),它将评估一个字符串公式。因此,您只需将AnswerShow
行更改为
Answer = Evaluate(Eqn.Statement1 & Ind.Indicator1 & Eqn.Statement2 & Ind.Indicator2 & Eqn.Statement3)