[英]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 語句的返回值分配給特定的單元格,如下所示:
添加 Select 案例結構。
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 語句下的代碼。
- 將變量結果的值寫入單元格 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 語句的結果為 output 一次單元格到當前單元格的右側?
您只需要:
cell.Offset(0, 1).Value = result
按照你的End Select
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.