【问题标题】:VBA return 2 variants in MsgBoxVBA 在 MsgBox 中返回 2 个变体
【发布时间】:2015-09-10 17:41:18
【问题描述】:

这是一个简单的数学定理演示的开始。

当我运行这个宏时,MsgBox 中没有出现 Coefficient 和 Degree。

Option Explicit
Sub Function1()
Dim Degree, Coefficient
MsgBox "Enter polynomial by terms."
Cells(1, 2).Value = Degree
Cells(2, 2).Value = Coefficient
    If IsNumeric(Degree) = True Then
    Else: MsgBox "IsNumeric(Degree)=False)"
        If IsNumeric(Coefficient) = True Then
        Else: MsgBox "IsNumeric(Coefficient)=False"
            MsgBox Coefficient & "x^" & Degree
        End If
    End If
End Sub

编辑:cmets 建议的新版本代码(仍然不起作用):

Option Explicit
Sub Function1()
Dim Degree, Coefficient
MsgBox "Enter polynomial by terms."
Degree = Cells(1, 2).Value
Coefficient = Cells(2, 2).Value
    If IsNumeric(Degree) = True Then
    Else: MsgBox "IsNumeric(Degree)=False)"
        If IsNumeric(Coefficient) = True Then
        Else: MsgBox "IsNumeric(Coefficient)=False"
            MsgBox Coefficient & "x^" & Degree
        End If
    End If
End Sub

【问题讨论】:

  • 您永远不会为DegreeCoefficient 赋值。相反,您将单元格 B1 和 B2 分配给空值,因为从未为度数和系数分配值。这些线应该是相反的吗?这样Degree = Cells(1, 2).Value??
  • 赋值顺序看起来不对,试试Degree = Cells(1, 2).Value等等。
  • 感谢您的建议。还是不行。
  • ...别傻了,但您的单元格中有数据B1 and B2 是吗?您是否在使用多个工作表/工作簿? B1B2 的值是多少?如果您单步执行宏(按F8),在Degree = Cells(... 行之后,将鼠标悬停在“Degree”上 - 它显示什么?它应该弹出B2 中的值。查看您编辑的代码,如果您的Degree 未设置,那么您如何获得消息框?我认为If IsNumeric(Degree) 将是FALSE,因此不应运行If 语句,因此不会显示任何消息框?
  • 你的外部If语句结构错误,所有代码都放在Else部分

标签: vba excel math office-2013


【解决方案1】:

您可能希望像这样重写您的程序:

Sub Function1()
    Dim Degree, Coefficient
    MsgBox "Enter polynomial by terms."
    Degree = Cells(1, 2).Value
    Coefficient = Cells(2, 2).Value

    If Len(Trim(Degree)) > 0 And IsNumeric(Degree) Then
        MsgBox "Degree is numeric"
    Else
        MsgBox "Degree is not numeric. Exiting"
        Exit Sub
    End If

    If Len(Trim(Coefficient)) > 0 And IsNumeric(Coefficient) Then
        MsgBox "Coefficient is numeric"
    Else
        MsgBox "Coefficient is not numeric. Exiting"
        Exit Sub
    End If

    MsgBox Coefficient & "x^" & Degree

End Sub

在单元格 B1 中,键入 1。在单元格 B2 中,键入 2。运行该过程,您应该会看到预期的结果。您可以从那里开始构建。

【讨论】:

  • 我认为 OP 将受益于执行上述 If 语句,而不是使用冒号 - 正如@user3964075 指出的那样,它可能会引起一些混乱。
猜你喜欢
  • 2022-01-19
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
相关资源
最近更新 更多