VBA 为什么 MsgBox 无限循环?

VBA why infinite loop with MsgBox?

如果有兴趣,宏的目标是使用计算机演示中值定理(比手工演示定理更强大)。因此数学标签。

我有 VBA 带有第一个 MsgBox 无限循环的宏。为什么这是无限的?我已经尝试重新定位部分代码来解决这个问题,似乎什么也没做。

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

您在不适当的地方修改了计数器。试试这个:

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

当您 运行 进入(无意的)无限循环时,首先要检查的是循环条件,看看为什么它永远不会失败并退出。在您的情况下,该测试是针对单元格的值,但重要的一点是计数器变量,因为它决定了哪些单元格(在此期间可能不会更改值)。

如果您手动浏览该程序,您会发现您在多个地方将其设置为 1,这实际上每次循环都会将其重置。所以即使你增加它,下一次它会回到 1 并且你重新开始。作为计数器的一般规则,您希望在循环外(上方)设置一次初始值,然后在循环体结束时递增它。