在Excel VBA中打开If / Then函数
我刚刚开始学习Excel VBA,并且遇到了特定练习的问题。 给定一列20个随机生成的0到100之间的整数列,我想编写一个VBA程序,如果该数字大于或等于50,则在其旁边的列中写入“通过”,如果数量less于50。
我的方法涉及使用一个从i = 1到20的循环函数,每个单元格(i,1)的If语句将在(i,2)中写入通过或失败。
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
我能不能深入了解我在做什么错误?
提前致谢!
尝试这样的事情…
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
-
您需要正确指定您的工作表,如工作
Sheets("Sheet1").Cells(...
-
当值小于60时,添加一个else子句来设置结果失败。否则,在第一次“通过”
-
如果在for循环中移动结束,紧跟分数检查之后…
以最less的变化进行修正如下:
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中,variables是函数的全局variables; 不是循环的本地。 正如所提到的,你也可以写下类似的东西:
result = "" if score >= 60 then result = "pass" sheet1....