我刚刚开始使用VBA编码,我很震惊:
对于一个单元格,该程序有效:
Dim score As Integer, result As String
score = Range("A1").Value
If score >= 60 Then
result = "pass"
Else
result = "fail"
End If
Range("B1").Value = result
一列细胞怎么样? Can循环可以用于此吗? 我的代码使用循环 - 但如何在范围内定义变量?
Dim score As Integer, result As String, I As Integer
score = Range("AI").Value
For I = 1 To 6
If score >= 60 Then
result = "pass"
Else
result = "fail"
End If
Range("BI").Value = result
Next I
提前致谢!
答案 0 :(得分:3)
几乎,你只需要使用字符串连接(&
)
Dim score As Integer, result As String, I As Integer
'score = Range("AI").Value
For I = 1 To 6
score = Range("A" & I).Value '// Needs to be inside the loop to update.
If score >= 60 Then
result = "pass"
Else
result = "fail"
End If
Range("B" & I).Value = result
Next I
这也可以写成:
For i = 1 To 6
Range("B" & i).Value = IIf(Range("A" & i).Value >= 60, "pass", "fail")
Next
答案 1 :(得分:2)
你也可以采用“公式”方法:
Range("B1:B6").FormulaR1C1 = "=If(RC1 >= 60, ""pass"", ""fail"")"
因此保持检查激活列A单元格值
中任何可能的后续更改或者,您是否只想拥有“静态”值:
With Range("B1:B100")
.FormulaR1C1 = "=If(RC1 >= 60, ""pass"", ""fail"")"
.Value = .Value
End With