如果感兴趣,宏的目标是使用计算机演示中间值定理(比手动演示定理更强大)。因此数学标签。
我有第一个MsgBox的无限循环的VBA宏。为什么这是无限的?我已经尝试重新定位部分代码来解决这个问题,似乎什么也没做。
Option Explicit
Sub Function1()
Dim Polynomial As String
Dim Sign
Dim counter As Integer
Dim Degree
Dim Coefficient
While Cells(counter + 1, 1).Value <> "" And Cells(counter + 1, 2).Value <> "" '+1 because top row occupied by column A, column B titles. If cell is empty stop.
counter = 1
MsgBox "Enter polynomial by terms."
counter = counter + 1
Degree = Cells(counter + 1, 1).Value 'A2
Coefficient = Cells(counter + 1, 2).Value 'B2
If (Coefficient < 0) Then
Sign = " - " ' if coefficient negative
Else
If Coefficient > 0 Then Sign = " + " ' if coefficient positive
End If
Polynomial = Polynomial & " " & Coefficient & "x^" & Degree 'concatenation string, list polynomial.
counter = 1
counter = counter + 1
Wend
MsgBox Polynomial
End Sub
答案 0 :(得分:2)
当你遇到(无意的)无限循环时,要检查的第一件事就是循环条件,看看为什么它永远不会使条件失败并退出。在你的情况下,该测试是关于单元格的值,但重要的是计数器变量,因为这是决定哪些单元格(在此期间可能没有改变值)的原因。
如果您手动浏览程序,您会看到您在多个位置将其设置为1,这通常会在循环中重置它。因此,即使你增加它,下一次通过它会回到1并且你从头开始。作为计数器的一般规则,您希望在循环外部(上方)设置一次初始值,然后在循环体的末尾递增它。
答案 1 :(得分:0)
您正在不适当的地方修改您的柜台。试试这个:
Option Explicit
Sub Function1()
Dim Polynomial As String
Dim Sign
Dim counter As Integer
Dim Degree
Dim Coefficient
counter = 1
While Cells(counter, 1).Value <> "" And Cells(counter, 2).Value <> ""
MsgBox "Enter polynomial by terms."
Degree = Cells(counter, 1).Value 'A2
Coefficient = Cells(counter, 2).Value 'B2
If (Coefficient < 0) Then
Sign = " - " ' if coefficient negative
Else
If Coefficient > 0 Then Sign = " + " ' if coefficient positive
End If
Polynomial = Polynomial & " " & Coefficient & "x^" & Degree 'concatenation string, list polynomial.
counter = counter + 1
Wend
MsgBox Polynomial
End Sub