2016-11-04 52 views
0

我想用vba对班级进行评分,这里是我的代码和信息。使用vba代码进行分级

3个条件,如果等级为100或以上,则显示100+,如果是50或以上,则显示50+。否则,它会显示在50以下。我试图在sheet2中创建一个按钮,所以当我按下它时,代码将在sheet1中运行。范围每个月都会有所不同,所以这就是为什么我试图循环到列A中的最后一行。我还向您展示了我试图产生的结果的快照。我的问题是,当我运行代码时,如果没有if,它会出错。需要建议或建议。

Sub Macro1() 
Dim I As Integer 
Dim lr As Integer 
Set ws = Worksheets("Sheet1") 
ws.Activate 
lr = Range("A" & Rows.Count).End(xlUp).Row 
For I = 2 To lr 
If Cells(I, 1).Value >= 100 Then Cells(I, 2).Value = "100+" 
    ElseIf Cells(I, 2).Value >= 50 Then Cells(I, 22).Value = "50+" 
     Else: Cells(I, 2).Value = "Below 50" 
End If 
Next I 
End Sub 

enter image description here

谢谢

+0

谢谢你,它就像一个魅力。 – sc1324

回答

2

你写的了If声明作为内联If,因为运行的代码是在同一行Then声明。要使用ElseElseIf,您需要使用不同的格式。试试这个:

If Cells(I, 1).Value >= 100 Then 
    Cells(I, 2).Value = "100+" 
ElseIf Cells(I, 2).Value >= 50 Then 
    Cells(I, 22).Value = "50+" 
Else 
    Cells(I, 2).Value = "Below 50" 
End If 

这将解决你的第一个错误“否则如果没有


就个人而言,我喜欢使用选择案例为这样的逻辑。

Select Case Cells(I, 1).Value 
    Case Is >= 100 
     Cells(I, 2).Value = "100+" 
    Case Is >= 50 
     Cells(I, 22).Value = "50+" 
    Case Else 
     Cells(I, 2).Value = "Below 50" 
End Select