Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA中的循环If/Then函数_Vba_Excel - Fatal编程技术网

Excel VBA中的循环If/Then函数

Excel VBA中的循环If/Then函数,vba,excel,Vba,Excel,我刚开始学习Excel VBA,但在一个特定的练习中遇到了问题。给定一列中由20个0到100之间的随机生成整数组成的列,我想编写一个VBA程序,如果该数字大于或等于50,则在其旁边的列中写入“通过”,如果该数字小于50,则写入“失败” 我的方法是使用一个从i=1到20的循环函数,每个单元(i,1)都有一个If语句,它将在(i,2)中写入pass或fail 我能了解一下我做错了什么吗 提前谢谢 变化量最小的修正如下: Sub CommandButton1_Click() 'Declare Vari

我刚开始学习Excel VBA,但在一个特定的练习中遇到了问题。给定一列中由20个0到100之间的随机生成整数组成的列,我想编写一个VBA程序,如果该数字大于或等于50,则在其旁边的列中写入“通过”,如果该数字小于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
    End If
Next i

End If
End Sub
记住,在VBA中,变量是函数的全局变量;不是本地的循环。正如前面提到的,你也可以写一些类似的东西:

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

试试这样的

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
  • 您需要正确指定您使用的工作表,例如
    工作表(“Sheet1”)。单元格(…

  • 添加一个else子句,当值小于60时,将结果设置为失败。否则,在第一次“通过”后,它将不会更改

  • 如果在for循环内,则在分数检查后立即移动端点


  • 我不确定您收到的错误是什么,但看起来确实需要为循环的每次迭代重置result的值。可能需要在循环内声明和初始化result。
    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