【问题标题】:If logic to write one of three texts into a cell如果将三个文本之一写入单元格的逻辑
【发布时间】:2020-01-25 15:58:07
【问题描述】:

我想根据结果在 E3 中写入文本 a、b 或 c。

代码使 Excel 崩溃。

Sub calculate()
Range("B2").Activate
Do While ActiveCell.Value <> ""
    If ActiveCell.Value + ActiveCell.Offset(0, 1) + ActiveCell.Offset(0, 2) = 3 Then
        ActiveCell.Offset(0, 3).Value = "Text A"
    ElseIf ActiveCell.Value + ActiveCell.Offset(0, 1) + ActiveCell.Offset(0, 2) = 2 Then
        ActiveCell.Offset(0, 3).Value = "Text B"
    ElseIf ActiveCell.Value + ActiveCell.Offset(0, 1) + ActiveCell.Offset(0, 2) < 2 Then
        ActiveCell.Offset(0, 3).Value = "Text C"
    End If
Loop
End Sub

【问题讨论】:

  • 您打算向下移动列还是只是一遍又一遍地检查B3??
  • 我已经编辑了代码。我想根据结果在 E3 中写文本 a、b 或 c
  • 在我看来你的 Do While .. Loop 应该只是一个 If .. Endif 块。除非在循环内更改 ActiveCell 值,否则它永远不会退出。
  • 1. 找到最后一行,如图所示HERE 2. 使用FOR 循环遍历该列中的单元格。如果您使用Do While ActiveCell.Value &lt;&gt; "",那么如果中间有一个空白单元格,代码将在中途停止。 3. 使用Select Case 而不是If-EndIf。它更容易阅读和维护。 注意这些只是我的建议,并不是必须遵循的硬性规定。

标签: excel vba loops if-statement


【解决方案1】:

使用一些变量!也许是这样的:

Sub calculate()
    Dim c As Range, v
    Set c = ActiveSheet.Range("B2") 

    Do While c.Value <> ""
        v = c.Value + c.Offset(0, 1).Value + c.Offset(0, 2).Value
        If v = 3 Then
            c.Offset(0, 3).Value = "Text A"
        ElseIf v = 2 Then
            c.Offset(0, 3).Value = "Text B"
        ElseIf v < 2 Then
            c.Offset(0, 3).Value = "Text C"
        End If
        Set c = c.offset(1, 0)
    Loop

End Sub

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2013-05-09
    • 1970-01-01
    相关资源
    最近更新 更多