如何将 case 语句的 return 值分配给 For 循环中当前单元格右侧的单元格?
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?
背景
在 VBA 中,您可以将 Select Case 语句的 return 值分配给 specific cells,如下所示:
Add the Select Case structure.
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
Explanation: Excel VBA uses the value of the variable score to test
each subsequent Case statement to see if the code under the Case
statement should be executed.
- Write the value of the variable result to cell 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 语句的结果输出一次单元格到当前单元格的右侧?
您只需要:
cell.Offset(0, 1).Value = result
关注你的End Select
背景
在 VBA 中,您可以将 Select Case 语句的 return 值分配给 specific cells,如下所示:
Add the Select Case structure.
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
Explanation: Excel VBA uses the value of the variable score to test each subsequent Case statement to see if the code under the Case statement should be executed.
- Write the value of the variable result to cell 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 语句的结果输出一次单元格到当前单元格的右侧?
您只需要:
cell.Offset(0, 1).Value = result
关注你的End Select