vba:迭代一个范围并一次更新另一个范围

时间:2015-09-04 15:22:48

标签: vba range

全部,

在表1的A栏中,我有以下n编号列表

12
250
1600
100
2000
:
:
34

我有一个可以嵌入代码的查找表

Min Max Grade
0   100  A
100 200  B
300 500  C
:
:
1000 2000 H
2000 5000 L
5000+     M

在表2的A栏中,我希望根据查找表显示与表单1中的数字对应的n个等级。我想只使用VBA而不是excel公式。我该怎么做?谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

你可以这样做。

Private Sub CommandButton1_Click()

    Dim ws1 As Excel.Worksheet
    Dim ws2 As Excel.Worksheet

    Set ws1 = ActiveWorkbook.Sheets("Sheet1")
    Set ws2 = ActiveWorkbook.Sheets("Sheet2")

    Dim lRow As Long
    Dim score As Integer
    Dim strGrade As String

    lRow = 1

    ws1.Activate
    'Loop through the rows getting the letter grade for the score.
    Do While lRow <= ws1.UsedRange.Rows.count

        'Get the score
        If ws1.Range("A" & lRow).Value = "" Then
            score = -1
        Else
            score = ws1.Range("A" & lRow).Value
        End If

        'Get the grade for the score
        Select Case score
        Case 0 To 100
            strGrade = "A"
        Case 100 To 200
            strGrade = "B"
        Case 300 To 500
            strGrade = "C"
        Case 1000 To 2000
            strGrade = "H"
        Case 2000 To 5000
            strGrade = "L"
        Case Is > 5000
            strGrade = "M"
        Case Else
            strGrade = "?"
        End Select

        'Write the grade to sheet 2
        ws2.Range("A" & lRow).Value = strGrade

        lRow = lRow + 1
    Loop

End Sub