在Excel VBA中循环If / Then函数

时间:2014-06-26 00:45:36

标签: excel vba excel-vba

我刚刚开始学习Excel VBA,而且我遇到了特定练习的问题。给定列中20个随机生成的0到100之间的整数列,我想编写一个VBA程序,如果数字大于或等于50,则在其旁边的列中写入“pass”,如果数字大于或等于50则为“fail”数字小于50.

我的方法涉及使用i = 1到20的循环函数,每个单元格(i,1)的If语句将在(i,2)中写入pass或fail。

Sub CommandButton1_Click()
'Declare Variables
Dim score As Integer, result As String, i As Integer

'Setup Loop function, If/Then function
For i = 1 To 20
    score = Sheet1.Cells(i, 1).Value
    If score >= 60 Then result = "pass"
    Sheet1.Cells(i, 2).Value = result
Next i

End If
End Sub

我可以深入了解我做错了吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

尝试这样的事情......

Sub CommandButton1_Click()
'Declare Variables
Dim score As Integer, result As String, i As Integer

'Setup Loop function, If/Then function
For i = 1 To 20
    score = Sheets("Sheet1").Cells(i, 1).Value
    If score >= 60 Then
        result = "pass"
    Else
        result = "fail"
   End If
    Sheets("Sheet1").Cells(i, 2).Value = result

Next i

End Sub
  1. 您需要正确指定与您合作的工作表,例如Sheets("Sheet1").Cells(...

  2. 当值小于60时,添加一个else子句将结果设置为失败。否则在第一次'pass'后它永远不会改变

  3. 如果在得分循环内,在分数检查后立即移动结束...

答案 1 :(得分:0)

更改量最少的更正如下:

Sub CommandButton1_Click()
'Declare Variables
Dim score As Integer, result As String, i As Integer

'Setup Loop function, If/Then function
For i = 1 To 20
    score = Sheet1.Cells(i, 1).Value
    If score >= 60 Then 
        result = "pass"
        Sheet1.Cells(i, 2).Value = result
    End If
Next i

End If
End Sub

请记住,在VBA中,变量是函数的全局变量;不是循环的本地。正如提到的那样,你也可以写下这样的东西:

result = ""
if score >= 60 then result = "pass"
sheet1....