如何定义范围内的variables

我刚开始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 

那么一列细胞呢? 循环可以为此工作? 我的代码使用循环 – 但如何定义范围内的variables?

 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 

提前致谢!

几乎,你只需要使用string连接( &

 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 

你也可以用“公式”的方法去做:

 Range("B1:B6").FormulaR1C1 = "=If(RC1 >= 60, ""pass"", ""fail"")" 

从而保持该检查对任何可能的后续更改列A单元格值有效

或者,如果您只想要“静态”值:

 With Range("B1:B100") .FormulaR1C1 = "=If(RC1 >= 60, ""pass"", ""fail"")" .Value = .Value End With