【问题标题】:How do I assign the return value of a case statement to the cell to the right of the current cell in a For loop?如何将 case 语句的返回值分配给 For 循环中当前单元格右侧的单元格?
【发布时间】:2020-01-21 19:50:12
【问题描述】:

背景

在 VBA 中,您可以将 Select Case 语句的返回值分配给specific cells,如下所示:

  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 loop 执行相同的操作。上面的代码针对一个实例执行此操作。但是,我想为每个单元格执行此操作,并将结果分类到右侧的单元格中。

尝试的解决方案

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

....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 语句的结果输​​出到当前单元格右侧的单元格?

【问题讨论】:

    标签: excel vba for-loop select-case


    【解决方案1】:

    你只需要:

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

    关注你的End Select

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      相关资源
      最近更新 更多