2015-09-04 118 views
1

所有更新另一範圍內的一個小區,VBA:通過一系列迭代,每次

在表1中,列AI具有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,我要N個對應於所述數字等級在片材1出現,基於該查找表。我想使用VBA而不是Excel公式。我該怎麼做?謝謝你的幫助!

+0

查找表在哪裏? – MatthewD

+0

它可以嵌入VBA代碼中,如'if then else'或'select case'邏輯。 – Zenvega

回答

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 
+0

這工作。謝謝,馬修! – Zenvega