首页 > 解决方案 > 如何将 case 语句的返回值分配给 For 循环中当前单元格右侧的单元格?

问题描述

背景

在 VBA 中,您可以将 Select Case 语句的返回值分配给特定的单元格,如下所示:

  1. 添加 Select Case 结构。

    Select Case score Case Is >= 80 result = "very good" Case Is >= 70 result = "good" Case Is >= 60 result = "sufficient" Case Else result = "insufficient" End Select

解释:Excel VBA 使用变量 score 的值来测试每个后续的 Case 语句,看是否应该执行 Case 语句下的代码。

  1. 将变量结果的值写入单元格 B1。

Range("B1").Value = result

这对我来说很简单,但是,我试图遍历一列单元格以使用for 循环做同样的事情。上面的代码针对一个实例执行此操作。但是,我想为每个单元格执行此操作,并将结果分类到右侧的单元格中。

尝试的解决方案

以下是我到目前为止使用的代码:

....variables defined at the beginning as strings
Set MyRange = Sheet6.Range("A2:A355")
For each cell In MyRange
    Select Case cell.Value
        Case Is = raid
            result = "area"
        Case Is = fifty
            result = "one"
        ... more cases ad nauseum
    End Select
Next

您可以使用上述范围方法方法分配特定单元格。但我想将生成的字符串分配到右侧的一个单元格(即在 B 列但在同一行)。因此我的问题...

问题

如何指定我希望在 VBA 的 For 循环中将 case 语句的结果输​​出到当前单元格右侧的单元格?

标签: excelvbafor-loopselect-case

解决方案


您只需要:

cell.Offset(0, 1).Value = result

跟随你的End Select


推荐阅读