2016-05-13 85 views
0

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

以及如何对单元格列?循环可以为此工作? 我的代码使用循环 - 但如何定义范围内的变量?

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 

在此先感谢!

回答

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 
+0

耶! :D我现在明白了;我的代码{私人小组CommandButton1_Click() 昏暗得分作为整数,导致作为字符串,确定作为整数 对于OK = 1至10 得分=细胞(确定,1)。价值 如果得分> = 60然后 结果= “通过” 否则 结果=“失败” 结束如果 细胞(确定,2)。价值=导致 接着确定 结束子} – mob

2

你也可以去一个 “公式” 的方法:

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

因此保持该检查对列中任何可能的后续更改保持活动状态一个单元格的值

,或者你应该想只有“静态”值:

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

它是相同的,因为值检查是在列“A”,它是柱1 – user3598756