选择案例结构

时间:2019-04-01 18:56:29

标签: excel vba

我的问题是以下,以下“选择大小写”,范围在A1:A100之间。在尝试以下代码后,对于我需要的100个进度结果,我只会得到一个结果。代码如下:

Private Sub CommandButton1_Click()

Dim score As Integer, result As String
 score = Range("A1").Value

Select Case score
    Case Is >= 80
    result = "very good"
    Case Is >= 70
    result = "good"
    Case Is >= 60
    result = "sufficient"
    Case Else
    result = "insufficient"
End Select

    Range("B1").Value = result

End Sub

3 个答案:

答案 0 :(得分:2)

如果您指定要在定义的范围内的每个单元格上执行相同的功能,则可以像这样进行FOR EACH循环:

Private Sub CommandButton1_Click()

Dim score As range, result As String
 set score = Range("A1:a100")

for each c in score.cells

Select Case c.value
    Case Is >= 80
    result = "very good"
    Case Is >= 70
    result = "good"
    Case Is >= 60
    result = "sufficient"
    Case Else
    result = "insufficient"
End Select

    c.offset(0,1) = result  'specifies the cell 1 column to the right of the current cell

next c
End Sub

答案 1 :(得分:1)

这就是我要做的。使用For ... Next循环在列出的A列范围内的单元格之间循环,然后将Select Case语句中的值放在B列相邻的单元格中,这是相当困难的事情。

Private Sub CommandButton1_Click()
    Dim score As Integer
    Dim result As String
    Dim xlCell As Range
        For Each xlCell In Range("A1:A100")
            score = xlCell
            Select Case score
                Case Is >= 80
                    result = "very good"
                Case 70 To 79
                    result = "good"
                Case 60 To 69
                    result = "sufficient"
                Case Is < 60
                    result = "insufficient"
            End Select
            xlCell.Offset(0, 1) = result
        Next xlCell
End Sub

答案 2 :(得分:1)

我个人不会在这里使用循环,这种方式比一次循环一个单元要快得多:

        var data = context.Set<Player>()
            .OrderBy(combinedOrder)
            .ToArray();

它放入一个公式来计算结果,然后强制进行计算(仅在将计算设置为手动时才需要,否则可以删除此行),然后将其复制并粘贴为值。

如果这是用于学校作业,并且被告知您要使用循环或案例陈述,那么可以使用被告知的陈述,否则,我建议您尽可能避免循环。